如何从在 JavaScript 中用作对象键的同名符号访问数据 [英] How to access data from same name Symbols used as object keys in JavaScript

查看:35
本文介绍了如何从在 JavaScript 中用作对象键的同名符号访问数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 JavaScript 符号,并且从我所读到的内容中,它们用于保护对象属性键覆盖.在下面的代码中,我创建了两个具有相同变量名称的符号并将它们用作对象键.我想知道如何访问分配给程序底部符号"键之一的数据.如果我完全误解了符号的目的,请指出.

I am learning about JavaScript symbols and from what I have read they are used to protect object property key overwrites. In the following code I create two symbols of the same variable name and use them as object keys. I want to know how to access the data assigned to either one of the "symbol" keys at the bottom of the program. If I'm misunderstanding the purpose of symbols altogether please point it out.

var id = Symbol("my id");             // Create a Symbol

var user = {

    name:"Bob",
    age:30,
    [id]:"my id 12345"               // Use it as a property key and add some data
}

var id = Symbol("my different id"); // Create a new Symbol

user[id] = "my different id 9876"   // Assign it with some new data

console.log(user);

/* The object contains both symbols. No overwrites!


{

    name: "Bob", 
    age: 30, 
    Symbol(my id): "my id 12345", 
    Symbol(my different id): "my different id 9876"

}


*/

推荐答案

如果我理解正确,你需要

If I understand you right, you need

var id = Symbol.for("my id");

var user = {
    name:"Bob",
    age:30,
    [id]:"my id 12345"     
}

var id = Symbol.for("my different id");

user[id] = "my different id 9876"

console.log(user[Symbol.for("my id")]); 
console.log(user[Symbol.for("my different id")]);

id 变量被重新赋值,所以你可以用它来获取 "my different id 9876" 符号不会被重新赋值.

The id variable is reassigned, so you can use it just to get "my different id 9876" Symbols will not be reassigned.

这篇关于如何从在 JavaScript 中用作对象键的同名符号访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆