+ 7

Javascript | Prototype, inheritance, constructor

Well, until recently I only used prototype to extends standard elements of Javascript. For example: Object.prototype.newMethod = blablabla... Now I'm trying to go deeper with something closer to OOP and I have see this two differents examples: //E.g: 1 myClass.prototype = myAnotherClass.prototype; //E.g: 2 myClass.prototype = new myAnotherClass(); Is there a difference? :O In addition what is doing the following line? myClass.prototype.constructor = Something; I thought that was to declare what method is the Class constructor but it seems not...or I made a mistake somewhere :S

10th May 2017, 6:28 AM
Geoffrey L
Geoffrey L - avatar
2 Réponses
+ 4
Object constructor prototypes are shared by all object instances. Classes were introduced in ES6 to "hide" in plain sight the already existing prototypal inheritance. From the Eg: 1 myClass inherits all the methods created on myAnotherClass prototype. So basically you have 2 different object constructors, each with it's on base Object prototype. All the methods defined on myAnotherClass.prototype are being shared with the myClass.prototype. So if a method is invoked by an object on myClass.prototype, it passes through prototypal chain to myAnotherClass.prototype for the method. In nutshell myClass still has it's own prototype but linked to that of myAnotherClass.prototype. For Eg: 2 myClass.prototype replaces it's prototype with myAnotherClass.
10th May 2017, 11:23 AM
Benneth Yankey
Benneth Yankey - avatar
+ 3
oh so you means in the first case it keeps a link between the abstract class and his instance(s), in the second case the instanciated class kind of take a snapshot at the moment to build it's own prototype and then cut the link with the original abstact class?
10th May 2017, 8:15 PM
Geoffrey L
Geoffrey L - avatar