一种新的原始数据类型Symbol,表示独一无二的值
基本用法
- Symbol.for() 方法和 Symbol.keyFor() 方法从全局的symbol注册表设置和取得symbol
- 在对象中查找 Symbol 属性:Object.getOwnPropertySymbols()
let s1 = Symbol('foo');
let s2 = Symbol('foo');
let s3 = Symbol.for('foo1');
let s4 = Symbol.for('foo1');
console.log(s1) //Symbol(foo)
console.log(s2) //Symbol(foo)
console.log(s1 === s2) //false
console.log(s3 === s4) //true
console.log(Symbol.keyFor(s1)) //undefined
console.log(Symbol.keyFor(s3)) //foo1
应用
- 消除魔术字符串
const shapeType = {
triangle: Symbol(),
circle: Symbol(),
}
function getArea(shape) {
let area = 0;
switch (shape) {
case shapeType.triangle:
area = 1;
break;
case shapeType.circle:
area = 2;
break;
default:
area = 0
break;
}
return area
}
console.log(getArea(shapeType.triangle)) // 1
console.log(getArea(shapeType.circle)) // 2
网友评论