Symbol

Symbol的介绍与创建

创建symbol
1
2
3
4
5
6
7
8
let s=Symbol();
console.log(s,typeof s);//Symbol() "symbol"
let s2=Symbol('aaa');
let s3=Symbol('aaa');
let s4=Symbol.for('aaa');
let s5=Symbol.for('aaa');
console.log(s2===s3);//false
console.log(s4===s5);//true
不能与其他数据进行运算
let result=s+100;
let result=s>100;
let result=s+s;

USONB  you are so niubility
u    undefined
s    string symbol
o    object 
n    null number
b    boolean

Symbol的使用

给对象添加方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
let game ={

}
/*let methods ={
up:Symbol(),
down:Symbol()
};
game[methods.up]=function(){
console.log('我可以改变形状');
}
game[methods.down]=function(){
console.log('我可以快速下降!!');
}
console.log(game);*/
let youxi={
name:"狼人杀";
[Symbol('say')]:function(){
console.log('我可以发言');
},
[Symbol('bomb')]:function(){
console.log('我可以爆炸');
}
}
console.log(youxi)

Symbol的内置属性

1
2
3
4
5
6
7
8
9
10
11
12
/*class Person{
static [Symbol.hasInstance](param){
console.log(param);
console.log("我被用来检测类型了");
}
}
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));//[1,2,3,Array(3)]

Symbol
https://blog-theta-ten.vercel.app/2021/06/28/Symbol/
作者
Chen
发布于
2021年6月28日
许可协议