我已经开始在JavaScript中查看符号,并开始在我的对象中使用它们来帮助解决名称冲突,但我仍然可以在使用它们时覆盖属性?我很难理解JavaScript中符号的含义。他们被说了很多,人们说他们很聪明,因为他们不会在对象中引起命名冲突,但我看不出怎么样?
// Create your object
let obj = {};
// Create your Symbol
let address = Symbol("the address symbol");
// Assign your Symbol as a key to a value
obj[address] = "123 Bond street";
// Return '123 Bond street'
console.log(obj[address])
// Another dev comes along
// Assigns an address property to your object
obj[address] = "456 Regent street";
// Your address property has been overwritten?
console.log(obj[address])
据我所知,我的代码仍然可以覆盖对象的属性?那么这个符号是如何帮助的?
我使用它们错了吗?
答案 0 :(得分:5)
您的印象似乎是,每次访问address
时,都会分配一个新的不同符号值,这是不正确的。
您所做的只是使用Symbol生成唯一值,然后将该值存储在address
变量中。这意味着当您稍后再次使用它时,您使用的是之前生成的相同符号。即使您没有使用符号,也会出现这种情况:
let obj = {}; // Create your object
let address = "some key name";
obj[address] = "123 Bond street";
console.log(obj[address]); // Return '123 Bond street'
// Another dev comes along
obj[address] = "456 Regent street"; // Assigns an address property to your object
console.log(obj[address]); // Your address property has been overwritten

简而言之,如果您存储符号,那么您只需存储一个保证唯一的值。但是,这并不能阻止你一遍又一遍地使用它。
Symbol
更合适的用途是阻止其他开发者在现有对象上创建 新 键,其名称与键相同由其他符号制成:
let obj = {}; // Create your object
let address = Symbol("some key name");
obj[address] = "123 Bond street";
console.log(obj[address]); // Return '123 Bond street'
// Another dev comes along
let newProp = Symbol("some key name");
obj[newProp] = "456 Regent street"; // Guaranteed unique new key is created
// There is no way the two properties would ever overwrite each other because each
// was created from a different Symbol
console.log(obj[address]);
console.log(obj[newProp]);