Characteristics and thinking of ES6 symbol

Liang said to himself 2021-05-03 19:19:54
characteristics thinking es6 es symbol


First, let's briefly talk about what is Symbol

  • Symbol yes ES6 New basic data type , It's unique , Like UUID equally ;
  • Symbol Is the function , By calling Symbol Function to create Symbol data ;
  • Symbol Or built-in objects , Provides a series of functions well-known Symbol Methods to change JS The internal behavior of language ;

Symbol The characteristics and use of

Example : establish Symbol data

  • Symbol There is no literal way to create , Neither can we. new Symbol() Constructor to create , Only by calling Symbol([description]) function , perhaps Symbol.for() To create .

// Symbol It is not allowed to use new Key constructor mode calls 
new Symbol()
// Uncaught TypeError: Symbol is not a constructor
// Create a non descriptive Symbol data 
let symbol1 = Symbol()
// Create... With description Symbol data 
let localSymbol Symbol('desc1')
// Create... In a global environment Symbol data 
let globalSymbol = Symbol.for('desc1')
// Global Registry Symbol and Symbol Function created Symbol It's different 
console.log(localSymbol === globalSymbol)
// Output :false
 Copy code 

characteristic :Symbol It's always the only one

  • Data is always unique , Not only in functions 、 Modules are even window The top-level scope is unique
// call Symbol function , In the current environment ( Function scope / Module scope ) Create unique symbol data , although toString The output looks the same , But the two are not equal 
let f1 = Symbol('flag')
let f2 = Symbol('flag')
console.log(f1,f2)
// Output :Symbol(flag) Symbol(flag)
console.log(f1 === f2)
// Output :false
console.log(f1 === 'flag')
// Output false
// call Symbol.for(key) Method , Create... In a global environment Symbol data .
// When the calling method is , Will be based on key Name to perform idempotent operations , If it doesn't exist, create , If it already exists, return 
let lock = Symbol.for('flag')
let lockFlag = Symbol.for('flag')
console.log(lock === lockFlag)
// Output :true
// Symbol() Functions and Symbol.for() Created Symbol The data are different 
console.log(f1 === lock)
// Output :false
// In the global environment, if you don't want to create , Just looking for , It can be done by Symbol.keyFor() Method 
console.log(Symbol.keyFor('flag')) // flag
console.log(Symbol.keyFor('test')) // undefined But it won't create 
 Copy code 

Example : Use Symbol To define constants

  • since Symbol Is the only sign , We can use Symbol To make constants .
  • We used to define constants like this :
const FRUIT = {
APPLE: 'APPLE',
BANANA: 'BANANA',
STRAWBERRY: 'STRAWBERRY'
}
// When called , We don't care value What is it? , Just look at key
console.log(FRUIT.APPLE)
// But if there's a fool , With a pineapple , But the value is written as apple , Judgment will explode 
const FRUIT = {
APPLE: 'APPLE',
BANANA: 'BANANA',
STRAWBERRY: 'STRAWBERRY',
PINEAPPLE: 'APPLE' // newly added 
}
// And by Symbol Definition words , It will avoid such problems 
const FRUIT = {
APPLE: Symbol(),
BANANA: Symbol(),
STRAWBERRY: Symbol()
}
function translate(FRUIT_TYPE){
switch (FRUIT_TYPE) {
case FRUIT.APPLE:
console.log(' Apple ')
break;
case FRUIT.BANANA:
console.log(' Banana ')
break;
case FRUIT.STRAWBERRY:
console.log(' strawberry ')
break;
default:
console.log(' Did not match ')
break;
}
}
translate(FRUIT.APPLE)
// Output : Apple 
 Copy code 

Example : Use Symbol To define a person's name

  • For example, in a class , I want to use a person's name as a unique identification , But there's no way to avoid repetition of names , adopt Symbol To achieve
const grade = {
[Symbol('Lily')]: {
address: 'shenzhen',
tel: '186******78'
},
[Symbol('Annie')]: {
address: 'guangzhou',
tel: '183******12'
},
// Allow duplicate names 
[Symbol('Lily')]: {
address: 'beijing',
tel: '172******10'
},
}
 Copy code 

characteristic :Symbol Type judgment and type conversion of

  • and String Same type ,Symbol The type can be through typeof Operator for type determination
let symbol = Symbol()
console.log(typeof Symbol)
// Output :symbol
 Copy code 
  • But and String The different types are ,Symbol There is no implicit automatic type conversion , Therefore, string splicing and arithmetic operations cannot be performed directly . But you can do explicit type conversion artificially , Like turning into String、Boolean、Number、Object
let symbolUUID = Symbol('uuid')
// You can't splice strings directly 
console.log(symbolUUID + ' test ')
// TypeError: Cannot convert a Symbol value to a string
// We can't do arithmetic directly 
console.log(symbolUUID + 1)
// TypeError: Cannot convert a Symbol value to a number
// But it's possible to do three eye operations boolean Judgment operation 
console.log(symbolUUID ? ' really ' : ' false ')
// Output : really 
console.log(String(symbolUUID) + ' test ')
// Output :Symbol(uuid) test 
// Equivalent to symbolUUID.toString()
 Copy code 

characteristic :Symbol Properties that can be used as objects key name

  • According to the specification ,Symbol Types can exist as data alone , It can also be used as an attribute of an object key name . also , Object properties key It can only be of string type or Symbol type , No other data type can be used as a property key,Boolean no way ,Number Not good either. .
  • But here's the thing , Need to be {[SymbolKey]: value} Array bracket to mount .
// As the property name of the object 
let desc = Symbol('desc')
let person = {
name: 'huilin',
sex: ' male ',
[desc]: ' Position : Front end engineer '
}
// Or it can be assigned this way :person[desc] = ' Position : Front end engineer '
console.log(person)
// Output :{name: 'huilin',sex: ' male ',Symbol('desc'): ' Position : Former engineer '}
 Copy code 
  • Symbol As a property name, it is weakly hidden
/*
* Get object properties in a normal way , Will automatically ignore Symbol The key value of the property is correct
*/
// If the above example goes on JSON.stringify() Format operation , Will ignore Symbol
console.log(JSON.stringify(person))
// Output :{name: 'huilin',sex: ' male '} 
// alike , image for Loop such a routine traversal operation , Will ignore Symbol
for(key in person){
console.log(key)
}
// Output : name sex
// Object.keys() Will ignore Symbol
console.log(Object.keys(person))
// Output : [ 'name', 'sex' ]
// Object.getProperty() Ignore Symbol
console.log(Object.getOwnPropertyNames(person))
// Output :[ 'name', 'sex' ]
/*
* Just get Symbol Method of key value pair of property
*/
console.log(Object.getOwnPropertySymbol(person))
// Output :[ Symbol(desc) ]
/*
* Get both general properties and Symbol Method of attribute
*/
console.log(Reflect.ownKeys(person))
// Output :[ 'name', 'sex', Symbol(desc) ]
 Copy code 

Example : adopt Symbol Simulate private properties or methods of objects

  • With the help of Symbol Weak concealment of attribute names , Simulate private properties
// Symbol Property name of type 
const id = Symbol()
class User {
constructor(idVal, name, age){
this[id] = idVal
this.name = name
this.age = age
}
checkId(id){
return this[id] === id
}
}
// Private property , External instances cannot be obtained directly 
let u = new User('001', 'Jay', 40)
console.log(u.name, u.age, u[id])
// Output :Jay 40 001
// But through exposure , Access to private properties 
console.log(u.checkId('001')) // true
console.log(u.checkId('002')) // false
 Copy code 

Example : utilize Symbol Data collection and integration

  • Take the example of Zhang Xinxu asking about xiaomeimei , Usually two objects merge ,key The same will cover :
let info1 = {
name: ' Light snow ',
age: 24,
job: ' Front end engineer ',
desc: ' Like watching movies , There's already a date '
}
let info2 = {
desc: ' I like dogs , I live in Nanshan District , Commuting by bus '
}
// Due to the use desc yes String As key,key The same will cover 
console.log(Object.assgin(info1,info2))
// Output :{name: ' Light snow ',age: 24,job: ' Front end engineer ',desc: ' I like dogs , I live in Nanshan District , Commuting by bus '}
 Copy code 
  • I'll use it instead Symbol As attribute key What's the name going to be like ?Symbol There will be no coverage
let info1 = {
name: ' Light snow ',
age: 24,
job: ' Front end engineer ',
[Symbol('desc')]: ' Like watching movies , There's already a date '
}
let info2 = {
[Symbol('desc')]: ' I like dogs , I live in Nanshan District , Commuting by bus '
}
// adopt Symbol As key, The merger will keep 
console.log(Object.assgin(info1,info2))
// Output :{name: ' Light snow ',age: 24,job: ' Front end engineer ',Symbol('desc'): ' Like watching movies , There's already a date ', Symbol('desc'): ' I like dogs , I live in Nanshan District , Commuting by bus '}
 Copy code 
  • so ,Symbol More concerned about value value , instead of key name . It can be concluded that ,Symbol It is convenient to collect and integrate data .
  • Take a real-life example , Like wall of wechat articles , The data values are all like , But the record won't be covered , The user's avatars will be listed ; Another example is the attendance book , The data value is time , It's very likely that it's the same time to get together and sign in , But it won't be covered , It's a list of records .
  • Back to JavaScript Grammar level , Maybe you think , Things like name conflict , The probability is very low ? It's necessary to add a new one Symbol Well ? But you think ,ES6 Of Module, Import and export can be aliased ; also ES6 Deconstruction of , You can directly get the property name of the object to the current environment ; So you still think the probability of name conflict is low ?
  • therefore Symbol Through the characteristics of collection and integration , When upgrading the basic framework version , Facilitate the downward compatibility of methods or variables with the same name .

System Symbol

  • In addition to creating your own Symbol Beyond mark ,ES6 A series of built-in well-know( as everyone knows ) Of Symbol Mark , Used to change JavaScript Bottom API act
API desc
Symbol.hasInstance When calling instanceof Operator to determine the instance , Will call this method
Symbol.isConcatSpreadable When calling Array.prototype.concat() when , Judge whether to expand
Symbol.unscopables Object specifies to use with When a keyword , Which attributes will be with Environmental exclusion
Symbol.match When executed str.match(obj) when , If the property exists, it is called , And return the return value of the method
Symbol.replace When executed str.replace(obj) Called when the , And return the return value of the method
Symbol.search When executed str.search(obj) Called when the , And return the return value of the method
Symbol.split When executed str.split(obj) Called when the , And return the return value of the method
Symbol.iterator When the object is for...of loop , call Symbol.iterator Method , Returns the object's default traverser
Symbol.toPrimitive Called when the object is converted to the original data type , Returns the original data type corresponding to the object
Symbol.toStringTag In this object, call toString Method called , Returns the return value of the method
Symbol.species Use this property when creating a derived object

Reference resources

版权声明
本文为[Liang said to himself]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503191542743f.html

  1. CSS layout
  2. Application scenario explanation of Vue dynamic component
  3. Redux learning notes 04 -- using multiple reducers to manage data
  4. After three months of typescript writing, what have I learned?
  5. Node family - what is a callback?
  6. React -- a simple implementation of render & create element
  7. JS learning simple usage of jquery
  8. Seamless love
  9. 小白前端入门笔记(12),设置哑链接
  10. Small white front-end entry notes (12), set dumb links
  11. Vue2. X opens composition API and TSX
  12. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  13. Flex learning notes
  14. The most essential closure article in the eastern hemisphere
  15. 2021-05-03 hot news
  16. Sword finger offer -- reverse order pair in array (JS Implementation)
  17. Working process of scaffold
  18. Use decorator mode to strengthen your fetch
  19. [JS] scope (Introduction)
  20. Employment information statistics network (interface document)
  21. Analysis of MVC
  22. [middle stage] please stay and join me in the backstage
  23. Understanding front end garbage collection
  24. [continuous update] front end special style implementation
  25. Flutter product analysis and package reduction scheme
  26. XPath positioning
  27. 前端开发css中的flex布局的使用
  28. The use of flex layout in front end development CSS
  29. JQuery核心函数和静态方法
  30. JQuery core functions and static methods
  31. Node family - understanding of blocking and non blocking
  32. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  33. Vue source code analysis (2) initproxy initialization proxy
  34. What's TM called react diff
  35. Summary of common front end data structure
  36. Useeffect in hooks
  37. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  38. Front end notes: virtual Dom and diff of vue2. X
  39. The best code scanning plug-in of flutter
  40. The simplest plug-in for rights management of flutter
  41. 21. Object oriented foundation "problems and solutions of object traversal"
  42. Discussion on hot micro front end: Google AdWords is a real micro front end
  43. Usecallback and usememo for real performance optimization
  44. 【前端圭臬】十一:从规范看 JavaScript 执行上下文(下)
  45. [front end standard] 11: Javascript execution context from the perspective of specification (2)
  46. Hexagonal六角形架构ReactJS的实现方式 - Janos Pasztor
  47. Transaction of spring's reactive / imperative relational database
  48. The implementation of hexagonal hexagonal reactjs Janos pasztor
  49. HTTP状态码:402 Payment Required需要付款 - mozilla
  50. HTTP status code: 402 payment required - Mozilla
  51. Factory mode, constructor mode and prototype mode
  52. Build the scaffold of react project from scratch (Series 1: encapsulating a request method with cache function based on Axios)
  53. Cocos Quick Start Guide
  54. Comparison of three default configurations of webpack5 modes
  55. A case study of the combination of flutter WebView and Vue
  56. CSS: BFC and IFC
  57. A common error report and solution in Vue combat
  58. JS: this point
  59. JS: prototype chain
  60. JavaScript series -- promise, generator, async and await