Hacker News new | ask | show | jobs
by ZachSaucier 1133 days ago
Couldn't you do elementReference.foo = whateverTypeYouWant? No need to restrict things to just the data attribute.

This wouldn't work if you need to know the order of the properties.

1 comments

This generally doesn’t play nice with TS code bases and is generally considered an anti-pattern since there’s chances for collisions etc , you might get away using a unique symbol index but it’s still not good design.
I'm not sure about DOM elements, but tacking random new properties onto Javascript objects can cause them to become deoptimized by the runtime.
Any reference for this?
I found [1] to be a pretty good summary of the key concepts that support the claim. The article, unfortunately, doesn't come right out and say it. But, it talks about how object shapes (a common JS object model) can be used as guards for inline caches (IC) to generate efficient machine code for property access. If you add a new property, you change the shape, which causes the cache guard to fail. That leads to deoptimization since the assumptions made about the call site when the code was compiled no longer hold. That call site is now either polymorphic or megamorphic, depending on the type of IC used and its level of polymorphism.

[1] -- https://mathiasbynens.be/notes/shapes-ics

Chances for collisions are pretty much nil if you use some prefix standard will never use, like $.

    el.$my_data = ...
And in practice it works just fine.