symbol
-
基础
let s0=Symbol('name'); console.log(s0);//Symbol(name)
-
Symbol做属性名
let symbolObj={ name:'symbol对象', [s0]:'symbol值' } console.log(symbolObj); //{name: "symbol对象", Symbol(name): "symbol值"}
-
属性名的遍历
使用Object.getOwnPropertySymbols()和Reflect.ownKeys()方法可以获取symbol属性console.log(Object.keys(symbolObj));//["name"] console.log(Object.getOwnPropertyNames(symbolObj));//["name"] console.log(Object.getOwnPropertySymbols(symbolObj));//[Symbol(name)] console.log(Reflect.ownKeys(symbolObj));//["name", Symbol(name)]
-
Symbol.for()和Symbol.keyFor()
通过Symbol()huo获取的相同键值的Symbol是不相等,通过Symbol.for()获取的相同键值的Symbol是相等的并且可以通过Symbol.keyFor()获取生成Symbol的键值。let t0=Symbol('jade'); let t1=Symbol('jade'); console.log(t0===t1);//false let s1=Symbol.for('jade') let s2=Symbol.for('jade') console.log(s1===s2);//true console.log(Symbol.keyFor(s1));//jade console.log(Symbol.keyFor(t0));//undefined
-
内置的symbol值
-
Symbol.hasInstance
当使用instanceof判断构造函数时调用const obj1={ [Symbol.hasInstance](value:any){ console.log(value); } } console.log({a:'a'} instanceof <any>obj1) // Objecta: "a"__proto__: Object // false
-
Symbol.isConcatSpreadable
该Symbol可以控制数组对象在使用contact方法时是否展开var alpha:any[] = ['a', 'b', 'c'], numeric:{ [key:string]:any } = [1, 2, 3]; numeric[<any>Symbol.isConcatSpreadable] = false; var alphaNumeric = alpha.concat(numeric); console.log(alphaNumeric); /* 0: "a" 1: "b" 2: "c" 3: (3) [1, 2, 3, Symbol(Symbol.isConcatSpreadable): false] length: 4 __proto__: Array(0) */
项目地址:https://gitee.com/jadeflicker/tslearn.git
chapter03分支