This question has already been answered:
- Prototype Inheritance 2 Responses
As a workout, I wrote 2 constructors with the inheritance of the second from the first. When I try to access the properties of constructor 1 from constructor 2, I get undefined
.
How to interact with properties from another constructor?
// ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡ 1 function Construct1() { // ΡΠ²ΠΎΠΉΡΡΠ²Π° this.constructor1 = 'Construct 1'; this.property1 = 'property 1'; } // ΠΌΠ΅ΡΠΎΠ΄ 1 Construct1.prototype.method1 = function() { return `${this.constructor1} -> method 1 -> ${this.property1}`; } let construct1 = new Construct1(); // ΠΏΡΠΎΠ²Π΅ΡΠΊΠ° ΠΌΠ΅ΡΠΎΠ΄Π° 1 console.log(construct1.method1()); // 'Construct 1 -> method 1 -> property 1' // ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡ 2 function Construct2() { // ΡΠ²ΠΎΠΉΡΡΠ²Π° this.constructor2 = 'Construct 2'; this.property2 = 'property 2'; } // Π½Π°ΡΠ»Π΅Π΄ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡΠ° 2 ΠΎΡ ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡΠ° 1 Construct2.prototype = Object.create(Construct1.prototype); Construct2.prototype.constructor = Construct2; // ΠΌΠ΅ΡΠΎΠ΄ 2 Construct1.prototype.method2 = function() { return `${this.constructor2} -> method 2 -> ${this.property2}`; } // ΠΌΠ΅ΡΠΎΠ΄ 3 Ρ Π½Π°ΡΠ»Π΅Π΄ΠΎΠ²Π°Π½ΠΈΠ΅ΠΌ ΠΌΠ΅ΡΠΎΠ΄Π° 1 Construct1.prototype.method3 = function() { return this.method1(); } let construct2 = new Construct2(); // ΠΏΡΠΎΠ²Π΅ΡΠΊΠ° ΠΌΠ΅ΡΠΎΠ΄Π° 2 ΠΈ 3 console.log(construct2.method2()); // 'Construct 2 -> method 2 -> property 2' console.log(construct2.method3()); // 'undefined -> method 1 -> undefined'