引入原因:
创建:
枚举:
共享符号值:
转换:
知名符号:
Symbol.hasInstance(obj): 判断obj是不是当前函数的实例,如ArraySymbol.hasInstance; 可以通过以下代码改变instanceof的默认行为: Object.defineProperty(MyObject, Symbol.hasInstance, {
value: function(v) {
return false;
}
});
Symbol.isConcatSpreadable let collection = {
0: "Hello",
1: "world",
length: 2,
[Symbol.isConcatSpreadable]: true
}; let messages = [ “Hi” ].concat(collection); console.log(messages.length); // 3 console.log(messages); // [“hi”,”Hello”,”world”]
Symbol.match 、 Symbol.replace 、 Symbol.search 、Symbol.split
Symbol.toPrimitive function Temperature(degrees) {
this.degrees = degrees;
} Temperature.prototype[Symbol.toPrimitive] = function(hint) {
switch (hint) {
case "string":
return this.degrees + "\\u00b0"; // 温度符号
case "number":
return this.degrees;
case "default":
return this.degrees + " degrees";
}
}; let freezing = new Temperature(32); console.log(freezing + “!”); // “32 degrees!” console.log(freezing / 2); // 16 console.log(String(freezing)); // “32°”
Symbol.toStringTag
age[Symbol.toStringTag] = ‘Node’; ‘Node’ age { age: 32, [Symbol(Symbol.toPrimitive)]: [Function], [Symbol(Symbol.toStringTag)]: ‘Node’ } age.toString(); ‘[object Node]’