Symbol的基本使用
ES6 引入了一种新的原始数据类型 引入了一种新的原始数据类型Symbol,表示独一无二的值。他是JavaScript语言的第七种数据类型,是一种类似于字符串的数据类型
Symbol特点
1) Symbol的值是唯一,用来解决命名冲突问题 的值是唯一,用来解决命名冲突问题
2) Symbol值不能与其他数据进行运算 值不能与其他数据进行运算
3) Symbol定义的对象属性不能使用for..in循环遍历,但是可以使用Reflect.ownKeys 来获取对象的所有键名
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//创建symbol
let s = Symbol();
//console.log(s,typeof s);
let s2 = Symbol('小凡');
let s3 = Symbol('小凡');
console.log(s2 == s3); //false
//Symbol.for 创建
let s4 = Symbol.for('小凡');
let s5 = Symbol.for('小凡');
console.log(s4,typeof s4)
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 stringg symbol
//o object
//n null number
//b boolean
</script>
</body>
</html>
Symbol创建对象属性:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//向对象中添加方法 up down
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('zibao')]:function(){
console.log('我可以自爆')
}
}
console.log(youxi)
</script>
</body>
</html>
Symbol内置值:
除了定义自己使用的 Symbol 值以外, ES6 还提供了 还提供了 11个内置的 Symbol值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// class Person{
// static [Symbol.hasInstance](param){
// console.log(param);
// console.log("我被用来检测类型了");
// return true;
// }
// }
// 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));
</script>
</body>
</html>