Hacker News new | ask | show | jobs
by jondwillis 1090 days ago
This [Symbol.dispose]() stuff is not intuitive to me. What are the brackets for? Is this an object property? Seems like a bad analogue to Swift’s defer and deinit keywords/methods.
3 comments

Are you familiar with [Symbol.iterator]()? It's doing the same thing.

{[someValue]: ...} is a pattern used when initializing computed keys on objects [1]. Some people might not encounter it often, though.

Symbol.* is sometimes used to implement language-level methods, like Symbol.dispose here or Symbol.iterator in my example below [2]. JS knows what those are for, and has well-defined and documented ways of using them.

I think — and I'm willing to be wrong — it's a pretty useful convention once it clicks, and while it might be confusing at first, I've come to like it. In the iterator example, you can see how you can create a dynamic data structure from a POJO (generating 52 cards from only the suits and ranks of a deck, and being able to treat it like an array). It's a useful way to encapsulate data and logic about a collection of data. When combined with generators, this pattern is extremely powerful. But again, this is why some people might not encounter it often.

1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

2. https://codesandbox.io/s/keen-swartz-7yrls3?file=/src/index....

JavaScript allows you to access and define object properties in several ways. The key thing to know here is that obj.foo, obj[“foo”], and obj[myProp] are all equivalent, where foo is a property of obj, and myProp is a variable containing the string “foo”.

This behavior is extended into object and class definitions, too. {[myProp]: “value”} creates an object whose property is the value of myProp, while {myProp: “value”} is an object with the property “myProp”. Because of the special nature of Symbols, the bracket notation is used when creating an object or class whose properties include a Symbol.

It's just a method definition using a globally defined symbol instead of your own method name which may clash with existing "dispose" implementations.

Agreed it's a little weird if you haven't been using variables as method names before though.