class Parent{
method(){
console.log("Parent");
}
}
class Child extends Parent{
method(){
console.log("Parent");
}
}
var child = new Child();
console.log(child.method);
console return method in child class which is a expected behaviour.
class Parent{
method = "sss"
}
class Child extends Parent{
method(){
console.log("Child")
}
}
var child = new Child();
console.log(child.method)
why does the console return method variable – "sss" in Parent class ?
2
Answers
From MDN
i.e. it masks the method because it is assigned around the time the constructor runs.
child.method
is a property (with a value that is a string) on the object itself. This masks themethod
on the prototype which is a function.The code below demonstrates.
You can see that in example
a
(your code) the string value formethod
is a property ofchild
itself, but you can dig through the prototype chain to get the function value from the class.In example
b
(with the public instance field removed), the method exists and can be called, but isn’t on thechild
itself (because its an instance of the class so it can search the prototype chain automatically because it isn’t masked).Is essentially a shortcut for:
Meaning that there are some important differences with:
In the
method = "sss"
variant,method
will be set as an own property of the created instance (new Child()
).Whereas defining a normal method
method() { console.log("Parent") }
will not be set as an own property of the instance. Instead it is set on the prototype chain.The constructor code only runs whenever you initialize an instance. Meaning that
this.method = "sss"
will always run after you’ve defined theParent
andChild
classes (whenever you create the instance withnew
).The final Child instance structure looks like this:
For more detailed info I suggest reading through the MDN Public class fields page.