i'm new to JavaScript and now just learning about classes.
Where i learned from (JavaScript.info), it is said that class extends
sets the prototype value of the parent class as __proto__
of the child class. Meaning i can just do something like:
(ChildClass.__proto__ === ParentClass) // true
But something else happens. Have a look at this block of code i wrote:
class thing {
constructor() {
console.log("hello")
}
doAThing() {
console.log("Doing a very cpu heavy thing.")
}
}
class extraThing extends thing {
doAnotherThing() {
console.log("doing another thing")
}
}
let thing1 = new thing();
let thing2 = new extraThing();
console.log(Object.getOwnPropertyNames(thing1.__proto__));
// [ 'constructor', 'doAThing' ] - links to itself because theres no __proto__ set...
console.log(Object.getOwnPropertyNames(thing2.__proto__));
// [ 'constructor', 'doAnotherThing' ] - links to itself although it extends "thing".?
I can't understand what's happening... Where does the child class take the parent class's methods from if its not in __proto__
.
By the way, as far as i understood, when you call a class with new
, it just runs the constructor as a normal constructor function, making classes just a syntactic suger (???).
And as far as i know, constructor functions (normal functions that are ran with new
) just return an object. So i assume that objects or instances that are returned by a class are just normal objects...
Although, i am aware that there are differences. Constructor functions that are ran under a class have a hidden property named [[IsClassConstructor]]
, but i don't understand how that would change the returned object, because as far as i know, it just changes the behavior of new
(like not letting you call a class without new
).