- 作为常量
- 作为属性
- 半隐藏属性
作为常量
const Java = Symbol();
const Ruby = Symbol();
const Perl = Symbol();
const Php = Symbol();
const VB = Symbol();
var lang = Java;//var lang = Ruby
if (lang === Java) {
console.log('Java的未来在哪里?');
}
if (lang === Ruby) {
console.log('再学个Ruby on Rails吧。');
}
作为属性
let s1 = Symbol("mySymbol");
let s2 = Symbol("mySymbol");
var obj = {};
obj[s1] = "helo";
obj[s2] = "world";
console.log(obj);
console.log(obj[s1]);
console.log(obj[s2]);
半隐藏属性
是指 知道隐藏属性的人可以取出来,不知道的就取不出来
const MYKEY = Symbol();
class User {
constructor(key,name,age){
this[MYKEY] = key;//这里就是 半隐藏属性,本来在这里可以写成 this.MYKEY=key
this.name = name;
this.age = age;
}
checkKEY(key){
return this[MYKEY] === key;
}
}
let user = new User(123, 'Curry', 29);
console.log(user.name, user.age, user[MYKEY]);
console.log(user.checkKEY(123)); //true
console.log(user.checkKEY(456)); //false
console.log(Object.keys(user)); //[ 'name', 'age' ] 这里没有打印出user[MYKEY]的值
console.log(JSON.stringify(user)); //{"name":"Curry","age":29} 这里也没有打印出user[MYKEY]的值
半隐藏属性
const MYKEY = Symbol();
class User {
constructor(key,name,age){
this[MYKEY] = key;
this.name = name;
this.age = age;
}
checkKEY(key){
return this[MYKEY] === key;
}
}
let user = new User(123, 'Curry', 29);
console.log(user.name, user.age, user[MYKEY]);
console.log(user.checkKEY(123)); //true
console.log(user.checkKEY(456)); //false
console.log(Object.keys(user)); //[ 'name', 'age' ]
console.log(JSON.stringify(user)); //{"name":"Curry","age":29}