javascript中的Symbol
Posted 低代码布道师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 code
name: "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 global
alert( localSymbol.description ); // name
keyFor只能访问到全局的,访问不到局部的
以上是关于javascript中的Symbol的主要内容,如果未能解决你的问题,请参考以下文章
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) JavaScript