const resource = {
[Symbol.dispose]: () => {
console.log("Hooray!");
},
};
Why not just const resource = {
dispose() {
console.log("Hooray!");
},
};
Why introduce this weird Symbol stuff? const resource = {
[Symbol.dispose]: () => {
console.log("Hooray!");
},
};
Why not just const resource = {
dispose() {
console.log("Hooray!");
},
};
Why introduce this weird Symbol stuff?> Prior to well-known Symbols, JavaScript used normal properties to implement certain built-in operations. For example, the JSON.stringify function will attempt to call each object's toJSON() method, and the String function will call the object's toString() and valueOf() methods. However, as more operations are added to the language, designating each operation a "magic property" can break backward compatibility and make the language's behavior harder to reason with. Well-known Symbols allow the customizations to be "invisible" from normal code, which typically only read string properties.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Essentially if they use dispose() like you mention, what happens if someone already has code that has dispose? And in future, avoid people accidentally calling these.
The symbol `Symbol.dispose` is special, unlike any normal string or identifier, because it didn't exist until the new standard, so existing code can't have been using it. This guarantees a level of backwards compatibility that wouldn't exist otherwise.
Also, you are assuming the consumer of a class is same as someone that used / uses the class. What if the library author has dispose and someone wrongly use using with it?
"Well-known" symbols include things like Symbol.iterator that make "for...of" loops possible, Symbol.asyncIterator for async for loops, Symbol.hasInstance for instanceOf, Symbol.toStringTag for toString, and others.
Vs this won't break anything existing.
Because this potentially break every existing object with a `dispose` symbol.
That is exactly why symbols were added in ES6, and what they're used for. You're just 8 years later.