Derek
Derek

Reputation: 12378

Javascript inheriting instance attributes?

function A(){
  // sort of like this
  // this.arr = [];
}

function B(){
  // not here though
  // this.arr = [];
}

B.prototype = new A(); // all B instances would share this prototypes attributes

// I want all B instances to have an arr attributes (array)
// of their own but I want the parent class to define it

var b1 = new B();
var b2 = new B();

b1.arr.push(1);
b2.arr.push(2);

b1.arr.length === 1; // should be true
b2.arr.length === 1; // should be true

I want write code in A that would define a arr variable for each instance of a child class B such that arr is a new object for each B instance. I could make this happen by setting this.arr = [] in the B constructor, but is this possible to accomplish with code written onto A instead?

Upvotes: 1

Views: 205

Answers (3)

roxxypoxxy
roxxypoxxy

Reputation: 3111

One way I can think of that to work is:

function A(){
   this.arr = [];
}

function B(){
   A.call(this); 
}

Upvotes: 0

Loïc Faure-Lacroix
Loïc Faure-Lacroix

Reputation: 13600

There is a big problem in your idea of inheritance in Javascript. In javascript, you really have objects and that's pretty much it. A constructor is a method that is called with new and create a new object.

This part of code isn't really right as you're creating a prototype using the object created from A... That said, you're not really using the prototype A. As inheritance per say doesn't really exist, you'll have to implement something that will call every constructors that are required to create object B.

B.prototype = new A();

You should use this method instead:

B.prototype = Object.create(A.prototype)

In this case, you'll have all the prototypes of A in B... But you'll still have to call the constructor of A if it is necessary.

function A() {
   this.arr = []
}

function B() {
    A.call(this)
}

Using more complex library, you could end up with inheritance and something similar to super in python. If you're really into that, you could also create a structure that will automatically call each constructor of each sub prototypes.

Upvotes: 2

maioman
maioman

Reputation: 18734

maybe this is what you're looking for:

B.prototype = Object.create(A.prototype);

With Object.create() you can create an object with a specific prototype, and I believe this is what you're trying to do.

Upvotes: 0

Related Questions