Home > Article > Web Front-end > Introduction to Symbol related knowledge in ES6 (code example)
This article brings you an introduction to Symbol-related knowledge in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
symbol is a type introduced in es6, and it also belongs to the category of primitive types (string, number, boolean, null, undefined, symbol)
let name = Symbol('xiaohesong') typeof name // 'symbol' let obj = {} obj[name] = 'xhs' console.log(obj[name]) //xhs
This thing is shareable. When it is created, it will check whether the symbol of this key is found globally. If it exists, the symbol will be returned directly. If it does not exist, it will be created and registered globally. .
let uid = Symbol.for("uid"); let object = { [uid]: "12345" }; console.log(object[uid]); // "12345" console.log(uid); // "Symbol(uid)" let uid2 = Symbol.for("uid"); console.log(uid === uid2); // true console.log(object[uid2]); // "12345" console.log(uid2); // "Symbol(uid)"The sharing mentioned here is global sharing, similar to global scope, and is shared in the entire environment.
let uid = Symbol.for("uid"); console.log(Symbol.keyFor(uid)); // "uid" let uid2 = Symbol.for("uid"); console.log(Symbol.keyFor(uid2)); // "uid" let uid3 = Symbol("uid"); console.log(Symbol.keyFor(uid3)); // undefined
The shared symbol uid3 does not exist in the global registry .So the corresponding key cannot be obtained. It can be seen that this is to obtain the corresponding key.
let uid = Symbol('uid') uid + ''
An error will be reported here. According to the specification, it will convert uid into Strings are added. If you really want to add, you can add String(uid) first and then add, but at present, it seems to be meaningless.
let uid = Symbol('uid') let obj = { [uid]: 'uid' } console.log(Object.keys(obj)) // [] console.log(Object.getOwnPropertyNames(obj)) // [] console.log(Object.getOwnPropertySymbols(obj)) // [Symbol(uid)]
es6 For this, the Object.getOwnPropertySymbols method was added.
Do you feel that Symbols are rarely used? In fact, there are still a lot of them used internally in es6.
Every function has this method. Maybe you are not very familiar with this method, but it is actually what instanceof does. That's right, es6 rewrites this method for you.
function Xiao(){} const xiao = new Xiao xiao instanceof Xiao // true
Actually es6 does that for you
Xiao[Symbol.hasInstance](xiao)
This is an internal method and does not support rewriting. Of course, we can rewrite it on the prototype.
Object.definePrototype(Xiao, Symbol.hasInstance, { value: (v) : Boolean(v) }) const x = new Xiao x instanceof Xiao //true 0 instanceof Xiao //false 1 instanceof Xiao //true
It can be found that we rewrite it to return whether the corresponding value is a boolean type.
This is different from other properties. It does not exist on some standard objects by default. Simply use
let objs = {0: 'first', 1: 'second', length: 2, [Symbol.isConcatSpreadable]: true} ['arrs'].concat(objs) //["arrs", "first", "second"]
. This is more useful. When performing type conversion, the object will try to convert to the original type, that is, through toPrimitive
.This method exists on prototypes of standard types.
When performing type conversion, toPrimitive
will be forced to call a parameter. In the specification, this parameter is called hint
. This parameter has three values ('number ', 'string', 'default') one of them.
As the name suggests, string
returns string
, number
returns number
, and default is not specified, the default.
So what is the default situation? In most cases, the default is numeric mode. (Except for date, its default situation is regarded as string mode)
In fact, there are not many default situations that are called during type conversion. Such as (==
,
) or when passing parameters to the constructor parameters of Date
.
number mode behavior in the case of numbers (priority from high to low)
First call valueOf, if it is a primitive type, Then return.
If the previous value is not the original value, then try to call toString. If it is the original value, then return
If it does not exist, then Report an error
string mode In the case of strings, the behavior is slightly different (priority from high to low)
First call toString , if it is the original value, then return
If the previous value is not the original value, then try to call valueOf, if it is the original value, then return
Throwing an error
Well, it feels a bit confusing, yes, let me explain the code.
let obj = { valueOf: function(){console.log('valueOf')}, toString: function(){console.log('toString')} } // console.log value is obj + 2 //valueOf obj == 2 // valueOf Number(obj) // valueOf String(obj) // toString
Through the above output, you can find that in most cases valueOf.
including the default case, the default is the number mode called, and most of them are the numbers called. mode, you can find that toString is the mode that calls string. So you can think that it is basically a numeric mode, unless it is a string mode.
Not very clear about this calling mode? It's okay, es6 exposes this internal method to the outside world, we can rewrite it and output the type of the hint. Come to
function Temperature(degrees) { this.degrees = degrees; } Temperature.prototype[Symbol.toPrimitive] = function(hint) { console.log('hint is', hint) }; let freezing = new Temperature(32); freezing + 2 // .. freezing / 2 // .. ...
the above types, you can try.
The above is the detailed content of Introduction to Symbol related knowledge in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!