Javascript inheritance and instance variables

I am trying to understand how inheritance works in JS. Suppose we have a class:

Class = function () { this.A = 'A'; this.B = 'B'; }; 

and we are trying to expand it

 SubClass = function () {}; SubClass.prototype = new Class(); 

I understand correctly that after inheritance properties A and B are common to all instances of SubClass , since they belong to the prototype? If so, how can Class be extended so that A and B not part of the prototype?

UPD: note that Class uses A and B , so I cannot declare them in SubClass.

Thank you in advance!

+4
source share
2 answers

All I want to do is make A and B available and specific to each instance.

A typical way to do this is to pass parameters and assign them to properties. Then you can use call to refer to the superclass. In other words:

 function Person( name, age ) { this.name = name; this.age = age; } function Student( name, age, grade ) { Person.call( this, name, age ); // call super-class with sub-class properties this.grade = grade; } Student.prototype = new Person(); Student.prototype.constructor = Student; var roger = new Student( 'Roger', 18, 'A+' ); 
+3
source

You can use properties in the parent class without a definition:

 Class = function () { this.sum = function() { return this.a+this.b; } }; SubClass = function () { this.a = 5; this.b = 6; }; SubClass.prototype = new Class(); var z = new SubClass(); z.sum(); //11 

Another way: create a function in the prototype that creates your properties:

 Class = function () { this.makeAB = function() { //called with context of SubClass this.A = 'A'; this.B = 'B'; } }; SubClass = function () { this.makeAB() }; SubClass.prototype = new Class(); var z = new SubClass(); zA = 'AAA'; zB = 'BBB'; var z2 = new SubClass(); console.log(z) console.log(z2) 
+1
source

Source: https://habr.com/ru/post/1445965/


All Articles