1
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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

One way I can think of that to work is:

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

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

1 Comment

It's not necessary to call new A(). As you're calling the constructor of A in the constructor of B, it will be as if you called the constructor twice. In the prototype of B you really only need to copy the prototype of A with Object.create.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.