复制 Symbol ( 'A' ) === Symbol ( 'A' ); // false
复制 const obj = {
[ 1 ] : 1 ,
[ 'a' ] : 'a' ,
[ Symbol ( 'A' )] : 'symbol'
}
Symbol
作为属性名,该属性不会被for...in
、for...of
遍历,Object.keys()
、Object.getOwnPropertyNames()
、JSON.stringify()
也无法返回。只能通过Object.getOwnPropertySymbols()
方法,获取指定对象的所Symbol
属性名。
复制 const symbolA = new Symbol ( 'A' ); // TypeError: Symbol is not a constructor
复制 const strSymbol = Symbol ( 'A' ); // Symbol(A)
const numSymbol = Symbol ( 1 ); // Symbol(1)
const boolSymbol = Symbol ( true ); // Symbol(true)
const obj = {
toString () {
return 'obj to string'
}
}
const objSymbol = Symbol (obj); // Symbol(obj to string)
const objSymbol2 = Symbol ({}); // Symbol([object Object])
const arrSymbol = Symbol ([ 1 , 2 ]); // Symbol(1,2)
复制 const symbol1 = Symbol ( 1 );
Number (symbol1); // TypeError: Cannot convert a Symbol value to a number
let n = 1 + symbol1; // TypeError: Cannot convert a Symbol value to a number
复制 const symbol1 = Symbol ( 1 );
Boolean (symbol1); // true
String (symbol1); // "Symbol(1)"
复制 const symbolA1 = Symbol ( 'A' ); // Symbol(A)
const symbolA2 = Symbol .for ( 'A' ); // Symbol(A)
const symbolA3 = Symbol .for ( 'A' ); // Symbol(A)
symbolA1 === symbolA2; // false
symbolA2 === symbolA3; // true
Symbol.for()
与Symbol()
都能够产生新的Symbol
。不过,Symbol.for()
产生的实例会登记在全局环境中供搜索。
复制 var symbolA = Symbol .for ( 'A' );
Symbol .keyFor (symbolA); // "A"
var symbolB = Symbol ( "B" );
Symbol .keyFor (symbolB) // undefined
复制 class MyClass {
[ Symbol .hasInstance](foo) {
return foo instanceof Array ;
}
}
[ 1 , 2 , 3 ] instanceof new MyClass () // true
复制 let arr1 = [ 'c' , 'd' ];
[ 'a' , 'b' ] .concat (arr1 , 'e' ); // ['a', 'b', 'c', 'd', 'e']
arr1[ Symbol .isConcatSpreadable]; // undefined
let arr2 = [ 'c' , 'd' ];
arr2[ Symbol .isConcatSpreadable] = false ;
[ 'a' , 'b' ] .concat (arr2 , 'e' ); // ['a', 'b', ['c','d'], 'e']
let obj = {length : 2 , 0 : 'c' , 1 : 'd' };
[ 'a' , 'b' ] .concat (obj , 'e' ); // ['a', 'b', obj, 'e']
obj[ Symbol .isConcatSpreadable] = true ;
[ 'a' , 'b' ] .concat (obj , 'e' ); // ['a', 'b', 'c', 'd', 'e']