3 ms·
Interesting, what exactly is it I am looking at? const resource = { [Symbol.dispose]: () => { console.log("Hooray!"); }, }; An object called resource,
by Alifatisk 3y ago
Interesting, what exactly is it I am looking at?
const resource = {
[Symbol.dispose]: () => {
console.log("Hooray!");
},
};
An object called resource, consisting on a anonymous function that logs Horray to the console. This is all fine and I am used to that.
The interesting part that stuck with me is "[Symbol.dispose]:". Why is it in a Array? What does this exactly do? It marks the anonymous function as disposable at the end of the code block? Correct?
{
[Symbol.dispose]: () => {...}
}
- jnspts 3y agoIt's not an array, but a way of using a variable as a key in an object. const name = "key" const example = { [name]: "value" }; This would result in const example = { key: "value" };
- singularity2001 3y agoSo if we know Symbol.dispose in advance we can simplify the code? Why did they make it so unwieldy especially since it is a new functionality not requiring backwards compatibility hacks?
- krona 3y agoSymbol.dispose is just a well-known symbol. Symbols are a fundamental part of the language, not a hack. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#well-known_symbols https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- mostlylurks 3y ago> So if we know Symbol.dispose in advance we can simplify the code? Symbol.dispose is not a string, but a symbol. Its value cannot be written out in the code, only referred to indirectly (that is basically what symbols are for), nor is there special syntax for properties with symbol keys like there is for properties with string keys, because that would be a nonsensical proposition due to the aforementioned fact. Thus, you cannot just write the property name directly, you have to use the computed property name syntax: [Symbol.dispose].
- anamexis 3y agoIt wouldn't be any different: const dispose = Symbol.dispose const resource = { [dispose]: () => {...} }
- masklinn 3y ago> So if we know Symbol.dispose in advance we can simplify the code? Symbol.dispose is Symbol.dispose. It's a singleton object and that's the sole reference to it. > Why did they make it so unwieldy especially since it is a new functionality not requiring backwards compatibility hacks? 1. Bare names in object keys are strings, so there needs to be an "escaping" syntax for non-string keys, that is what the brackets have done since 2015, in order to support the addition of... 2. Non-conflicting keys, which are what symbols are: symbols are guaranteed not to conflict with any string, and even to be unique unless they're created using `Symbol.for` (which accesses and stores into a global registry, this allows adding protocol methods to all objects without the risk of breaking existing any (by triggering new and unexpected behaviour).