javaScript 學習零散筆記(2) ---- 新的資料型別Symbol
阿新 • • 發佈:2019-02-03
此文是在學習《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
*登記的地方是針對全域性的,所以即時是從iframe去取值,仍然是相同的{ let x1 = Symbol.for('test'); Symbol.keyFor(x1);//test let x2 = Symbol('test'); Symbol.keyFor(x2);//undefined }
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;
}
}