本文主要是介绍javascript中的Symbol,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Symbol用来标识一个唯一标识例如id
let id = Symbol();
Symbol也可以按名字命名
// id is a symbol with the description "id"
let id = Symbol("id");
即时描述一样,也表示为不同的值
let id1 = Symbol("id");
let id2 = Symbol("id");alert(id1 == id2); // false
Symbol不能自动转换为字符串
let id = Symbol("id");
alert(id); // TypeError: Cannot convert a Symbol value to a string
但是可以显示的调用方法获取值
let id = Symbol("id");
alert(id.toString()); // Symbol(id), now it works
alert(id.description); // id
Symbol可以作为对象的影藏属性
let user = { // belongs to another codename: "John"
};let id = Symbol("id");user[id] = 1;alert( user[id] ); // we can access the data using the symbol as the key
如果在对象中定义需要使用中括号
let id = Symbol("id");let user = {name: "John",[id]: 123 // not "id": 123
};
在for…in循环中不会读取Symbol
let id = Symbol("id");
let user = {name: "John",age: 30,[id]: 123
};for (let key in user) alert(key); // name, age (no symbols)// the direct access by the symbol works
alert( "Direct: " + user[id] );
对象拷贝的时候Symbol也会被拷贝
let id = Symbol("id");
let user = {[id]: 123
};let clone = Object.assign({}, user);alert( clone[id] ); // 123
全局Symbol定义的值是一样的
// read from the global registry
let id = Symbol.for("id"); // if the symbol did not exist, it is created// read it again (maybe from another part of the code)
let idAgain = Symbol.for("id");// the same symbol
alert( id === idAgain ); // true
访问全局Symbol
// get symbol by name
let sym = Symbol.for("name");
let sym2 = Symbol.for("id");// get name by symbol
alert( Symbol.keyFor(sym) ); // name
alert( Symbol.keyFor(sym2) ); // id
let globalSymbol = Symbol.for("name");
let localSymbol = Symbol("name");alert( Symbol.keyFor(globalSymbol) ); // name, global symbol
alert( Symbol.keyFor(localSymbol) ); // undefined, not globalalert( localSymbol.description ); // name
keyFor只能访问到全局的,访问不到局部的
这篇关于javascript中的Symbol的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!