问题
I have started to take a look at Symbols in JavaScript, and have started to use them in my Objects to help with name clashes, but I can still overwrite properties when using them? I'm having a really hard time to understand what the point of Symbols are in JavaScript. They are spoken about a lot and people say they are brilliant because they don't cause naming conflicts in Objects, but I can't see how?
// 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])
As far as I can see from my code I can still overwrite properties on the Object? So how did the Symbol help?
Am I using them wrong?
回答1:
It appears that you are under the impression that every time you access address
a new and different Symbol value will be assigned, which is not correct.
All you are doing is using Symbol to generate a unique value and then you are storing that value in the address
variable. That means that when you use it again later, you are using the same Symbol you generated earlier. This would be the case even if you weren't using Symbol:
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
In short, if you store a Symbol, you've done nothing more than stored a value that's guaranteed to be unique. But, that doesn't stop you from using it over and over.
A more appropriate use for Symbol
would be to prevent another developer from creating a new key on an existing object with the same name as keys that were made from other Symbols:
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]);
来源:https://stackoverflow.com/questions/50806000/javascript-symbols-are-not-stopping-name-clashes-in-objects