Open LeaVerou opened 6 months ago
No objections here, I think that sounds good. What does [[ Class ]]
mean?
What does
[[ Class ]]
mean?
Warning: infodumping ahead 😅
When you do Object.prototype.toString.call(obj)
, you get a string like "[object Foo]"
. The Foo
in there is the object’s internal type, which used to be called [[ Class ]]
. You may still see "[[ Class ]]
being used since AFAIK there is no better term to describe the concept).
Reading [[ Class ]]
is generally more robust than typeof
or instanceof
, since:
typeof
does not give you useful info when you’re dealing with different types of objects (eveyrthing is just "object"
) and is thrown by primitive wrapper objects, i.e. typeof new String("foo")
is "object"
, not "string"
globalThis
, the same constructor objects from different contexts will not be equal. E.g. if you grab a reference to an array from an <iframe>
and try to do foo instanceof Array
in the parent frame, it will be false, because it's an instance of a different Array
class. That's why we got Array.isArray()
eventually, because simply checking if something is an array was incredibly painful if you want to do it in a robust way (and while you can cut corners on robustness when working on an app you control, since you know what code you're dealing with, you can't when developing a library that needs to work in environments you don't control.In the past only native objects had the privilege of having a [[ Class ]]
that was not "Object"
, but now authors can use Symbol.toStringTag
to override the default.
[[ ]]
denotes an internal slot, i.e. a property or method that is implemented by the JS runtime but cannot be accessed or modified directly. See https://medium.com/jspoint/what-are-internal-slots-and-internal-methods-in-javascript-f2f0f6b38de
Following up on this, how do you get the [[ Class ]]
for an object?
Accidentally closed this
In the initial Treecle port, I removed all the functionality that supports type => something object literals and instead it only supports functions for these things. I instead added code to Vastly to transform object literals into functions.
But it just dawned on me: this would be very useful in Treecle too, it's just that we can't depend on
node.type
returning a useful type. But we could have aconfig.getType()
method, which by default returns the object[[ Class ]]
, but can be overridden (e.g. Vastly would doconfig.getType = n => n.type
).Any objections @adamjanicki2 ?