一日客家話:中文:茄子 客語:雕吹
當作是一種語言擴充機制
Symbol(描述Symbol)
會產生唯一 unique Symbol,可以解決相同名被覆蓋Symbol.for()
JavaScript有一個全域的Symbol registry註冊狀態(犀牛JS大全翻譯)
Symbol.for("key")
Symbol()不會回傳相同的值
Symbol.for()相同字串關聯就會回傳相同值
Symbol()
functionlet s = Symbol('wendy');
console.log(typeof s); //symbol
Symbol.for()
functionlet c = Symbol.for('wendy');
console.log(c, typeof c);//Symbol(wendy) symbol
Symbol( )有唯一性
let a = Symbol('wendy');
let b = Symbol('wendy');
console.log(a===b)//false
Symbol.for()
let c = Symbol.for('wendy');
let d = Symbol.for('wendy');
console.log(c === d);//true
console.log(c, typeof c);//Symbol(wendy) symbol
console.log(d, typeof d);//Symbol(wendy) symbol
let a = Symbol('wendy');
let b = Symbol('wendy');
console.log(a, typeof a);//Symbol(wendy) symbol
console.log(b, typeof b);//Symbol(wendy) symbol
console.log(a === b);//false
let string = a.toString();
console.log(string);//Symbol(wendy)
無法四則運算:
let value1 = Symbol('1');
let value2 = Symbol('2');
console.log(value1 + value2);//error
一個基本的物件:是由properties特性:key和value 組成的無序群集
properties name(key) : 通常是字串
物件裡的key 使用 Symbol
let apple = Symbol('red apple');
let myFruit = {
[apple]: '2',
};
console.log(myFruit);
//{ [Symbol(red apple)]: '2' }
console.log(Object.getOwnPropertyNames(myFruit));
//[]
console.log(Object.getOwnPropertySymbols(myFruit));
//[ Symbol(red apple) ]
getOwnPropertyNames
:
回傳一個array裡面放所有Property的Names
getOwnPropertySymbols
:
1.返回:symbol的array
2.創建symbol 才有symbol的array
當想要使用相同properties name
因為Symbol 具有唯一性所以不會被覆蓋
const fruit = 'fruit';
let symbol1 = Symbol(fruit);
let symbol2 = Symbol(fruit);
let myObject = {};
myObject[symbol1] = 'apple';
myObject[symbol2] = 'banana';
console.log(myObject);
//{ [Symbol(fruit)]: 'apple', [Symbol(fruit)]: 'banana' }
但無法使用:for/in、for...of
for/in:列出object的key值
以Symbol為propertie name是不會被列舉
const fruit = 'fruit';
let symbol1 = Symbol(fruit);
let symbol2 = Symbol(fruit);
let myObject = { drink: 'water' };
myObject[symbol1] = 'apple';
myObject[symbol2] = 'banana';
console.log(myObject);
//{ drink: 'water', [Symbol(fruit)]: 'apple', [Symbol(fruit)]: 'banana' }
console.log(myObject[symbol1]); //apple
console.log(myObject[symbol2]); //banana
for (let x in myObject) {
console.log(x); //drink
}
尚硅谷 ES6 Symbol的介绍与创建
mdn
ES6 and Typescript Tutorial - 36 - Symbols
JavaScript 大全
The Ultimate Guide to JavaScript Symbol