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只能访问到全局的,访问不到局部的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

低代码布道师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值