基本使用
特點
- Symbol 的值是唯一的,用來解決命名沖突的問題
- Symbol 值不能與其他資料進行運算
- Symbol 定義的對象屬性不能使用 for…in 循環周遊,但是可以使用Reflect.ownKeys 來擷取對象的所有鍵名
//建立Symbol
let s = Symbol();
// console.log(s, typeof s);
let s2 = Symbol('st');
let s3 = Symbol('st');
//Symbol.for 建立
let s4 = Symbol.for('st');
let s5 = Symbol.for('st');
//不能與其他資料進行運算
// let result = s + 100;
// let result = s > 100;
// let result = s + s;
let game = {
name:"狼人殺",
[Symbol('say')]: function(){
console.log("我可以發言")
},
[Symbol('zibao')]: function(){
console.log('我可以自爆');
}
}
console.log(game)
console.log(game[Reflect.ownKeys(game)[1]]());
class Person{
static [Symbol.hasInstance](param){
console.log(param);
console.log("我被用來檢測類型了");
return false;
}
}
let o = {};
console.log(o instanceof Person);
const arr = [1,2,3];
const arr2 = [4,5,6];
arr2[Symbol.isConcatSpreadable] = false;
console.log(arr.concat(arr2));