Creating Symbols
声明
Symbol1let symbolVal = Symbol()Symbol的描述信息会被存储在内部属性
[[Description]]上,当调用toString()时,会读取这个属性12let symbolWithDescription = Symbol('first name')symbolWithDescription.toString() // 'Symbol(first name)'使用
typeof判断类型12let symbol = Symbol('test symbol')console.log(typeof symbol) // 'symbol'
Sharing Symbols
Symbol.for(key):创建被共享的Symbol,key相同的Symbol相等123let uid1 = Symbol.for('uid')let uid2 = Symbol.for('uid')uid1 === uid2 // trueSymbol.for(key)的创建步骤- 先搜索
the global symbol registry - 如果注册表中存在标识为
key的Symbol,则返回这个Symbol。 - 如果不存在,则创建一个新的Symbol,并将这个Symbol注册到注册表中,其标识为
key
- 先搜索
Symbol.keyFor(Symbol):访问shared Symbol的key
获取一个对象的Symbol属性
Object.getOwnPropertySymbols():只获取Symbol属性Reflect.ownKeys():获取所有的属性,包括Symbol属性
Exposing Internal Operations with Well-known Symbol
Symbol.hasInstance:可以通过修改Symbol.hasInstance改变instanceof的默认行为1234567891011function MyObject() {// empty}// 必须通过Object.defineProperty去修改Symbol.hasInstanceObject.defineProperty(MyObject, Symbol.hasInstance, {value: function(v) {return false;}});let obj = new MyObject();console.log(obj instanceof MyObject); // falseSymbol.isConcatSpreadable:当使用concat(param)时,用于确定param是否应该展开123456789let collection = {0: "Hello",1: "world",length: 2,[Symbol.isConcatSpreadable]: true};let messages = [ "Hi" ].concat(collection);console.log(messages.length); // 3console.log(messages); // ["hi","Hello","world"]Symbol.iterator:返回一个iteratorSymbol.speciesSymbol.match、Symbol.replace、Symbol.search、Symbol.split:创建类似regular expressions的对象Symbol.toPrimitive:重写类型转化时的默认行为12345678910111213141516171819function Temperature(degrees) {this.degrees = degrees;}Temperature.prototype[Symbol.toPrimitive] = function(hint) {switch (hint) {case "string":return this.degrees + "\u00b0"; // degrees symbolcase "number":return this.degrees;case "default":return this.degrees + " degrees";}};var freezing = new Temperature(32);console.log(freezing + "!"); // "32 degrees!"console.log(freezing / 2); // 16console.log(String(freezing)); // "32°"Symbol.toStringTag123Array.prototype[Symbol.toStringTag] = "Magic";var values = [];console.log(Object.prototype.toString.call(values)); // "[object Magic]"Symbol.unscopables:定义了在with声明的作用域里会被排除的属性