Eugeny89
Eugeny89

Reputation: 3731

javascript inheritance and instance variables

I'm 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 extend it

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

Do I understance correctly that after inheritance properties A and B are common for all instances of SubClass, since they belong to it's prototype? If yes, how can Class be extended so that A and B do not be part of prototype?

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

Thank you in advance!

Upvotes: 4

Views: 2009

Answers (2)

elclanrs
elclanrs

Reputation: 94101

All I want is to make A and B be accessible and specific for each "instance"

The typical way of doing this is to pass parameters and assign them to properties. Then you can use call to reference the super class. 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+' );

Upvotes: 3

Damask
Damask

Reputation: 1254

You can use properties in parent class without defining:

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 function in prototype which 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();
z.A = 'AAA';
z.B = 'BBB';

var z2 = new SubClass();

console.log(z)
console.log(z2)

Upvotes: 1

Related Questions