I'm writing some tests about the comparison between Class
and Object
in Javascript. And I have some doubt about the real objective with Class
in JS.
If everything is an object
(except primitives types) is correct to state that:
class Foo {
static anyFunc () {}
}
const FooInstance = new Foo();
is equal
const FooInstance = {
anyFunc () {}
}
?
How I can measure the performance/memory allocated/sizeof of these implementations? Can be in C++ or JS.
Thanks so much!
const FooInstance = {
anyFunc () {}
}
FooInstance
in this case is directly an instance of Object
. If you look at its prototype chain, it's immediately Object
. anyFunc
method will be found on the instance itself.
class Foo {
static anyFunc () {}
}
const FooInstance = new Foo();
FooInstance
in this case is an instance of Foo
(and Object
too since all objects descend from it). If you look at its prototype chain it will have the prototype of Foo
first, then the prototype of Object
next. Additionally, anyFunc
is not a method on the instance (nor the prototype). It will be attached on the constructor itself (i.e. Foo.anyFunc()
or FooInstance.constructor.anyFunc()
, but not FooInstance.anyFunc()
).
In short, no. They're not equal.
Visually, the chain would look like:
// First case:
instance ---> Object.prototype
- anyFunc
// Second case:
instance -> Foo.prototype -------> Object.prototype
- constructor (Foo)
- anyFunc
How I can measure the performance/memory allocated/sizeof of these implementations?
It's negligble. Don't worry about it. Or worry about it only when it becomes a problem.