we know that classes are just functions in javascript and classes is just an abstraction, syntactic sugar, whatever you want to call it, over its prototype-based inheritance. For example:
class foo {
bar() {}
}
is transformed to:
function foo() {}
foo.prototype.bar = function() {};
but if we use a public instance as
class foo {
bar = "Hello World";
}
we cannot access the bar
instance properies as
foo.prototype.bar
(undefined)
I know we have to create a new instance to access it like:
var instance = new foo();
console.log(instance.bar); // "Hello World"
but somehomw bar
property must be baked in foo
‘s proptotye, so where is it?
learn how pubilc instance is used internally by ES6
2
Answers
These fields are not placed on the prototype. Instead, they are directly attached to each instance of the class
With the field declaration
bar = "Hello World";
inside your foo class, when you create an instance of foo, JavaScript automatically assigns bar to that instance within its constructor. So it is equivalent to thisThat’s why you cannot access bar through foo.prototype.bar as it’s not part of the prototype. It is an instance variable that is unique to each object instantiated from the class.
The bar property isn’t "baked" into foo’s prototype. It is directly attached to each object instantiated from the foo class.
The instance of the class is simply a JS object. An interesting thing is that
instance.rebar
does not get logged in the following example when logging the instance while you can still access it throughinstance.rebar
To keep it short: The class instance is not a function