此文是在学习《ECMAScript 6 入门》-- 阮一峰 过程中的记录,在此非常感谢他的分享。《ECMAScript 6 入门》让我获益匪浅
1: Symbol 不是对象,不能new Symbol();
2: Symbol() 每次返回的值是不同的{
let x1 = Symbol();
let x2 = Symbol();
x1 == x2; //false
}
3: Symbol()支持传入参数,但是同样的参数返回的结果依然是不同的
{
let x1 = Symbol('test');
let x2 = Symbol('test');
x1 == x2; //false
}
4: Symbol.for() 登记方法,并能返回相同的参数获得的Symbol值
{
let x1 = Symbol.for('test');
let x2 = Symbol.for('test');
x1 == x2; //true
}
*但是在此处有需要注意的点:
对于一方没有登记的相同字符串,仍不能得到同样的Symbol值
{
let x1 = Symbol('test');
let x2 = Symbol.for('test');
x1 == x2; //false
}
5:Symbol.keyFor() 返回登记的Symbol值得key, 同样没有登记的不能返回key
{
let x1 = Symbol.for('test');
Symbol.keyFor(x1);//test
let x2 = Symbol('test');
Symbol.keyFor(x2);//undefined
}
*登记的地方是针对全局的,所以即时是从iframe去取值,仍然是相同的
6:Symbol.hasInstance 属性
对象的Symbol.hasInstance属性在使用instanceof时被调用
class Myclass{
[Symbol.hasInstance](foo){
return foo instanceof Array;
}
}
[1,2,3] instanceof new Myclass();//true
7: 对象的Symbol.isConcatSpreadable属性等于一个布尔值,表示该对象用于Array.prototype.concat()时,是否可以展开。
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']
class A1 extends Array {
constructor(args) {
super(args);
this[Symbol.isConcatSpreadable] = true;//定义在类的实例上
}
}
class A2 extends Array {
constructor(args) {
super(args);
}
get [Symbol.isConcatSpreadable] () {//定义在类上
return false;
}
}