Question

I'm trying to understand javascript inheritance/prototypes.

I did this:

function Foo(par){
    this.prop= par;
    this.propTwo = par;
}
function Bar(par){
    this.p=par;
}
Bar.prototype = new Foo();

If I do:

var myBar = new Bar("value");

myBar.propTwo is undefined (I assume this because even If I overwrite the prototype,I'm explicitly using the Bar "construct function" << please correct me if I'm wrong in this assumption.

if I want that Bar inherit from Foo, how should I create an instance of Bar or rewrite the constructs function(s) to get the propTwo also defined/assigned when creating myBar object (notice the same argument passed is assigned to both props) ?

I'm not even sure if I'm doing something "good" here, so if I'm totally wrong it's okay say it, if can be fixed please don't hesitate in details.

Update: I have selected Ethan Brown's answer as the correct because of 1 min. of difference (nothing personal). Both explanation works well and use two different ways (actually the idea is the same, one use "apply" the other one "call").

Also Bergi's link/comment it turns out to be an extended answer/justification about why not using this approach:

What is the reason to use the 'new' keyword here?

Thanks for the answers/material.

Was it helpful?

Solution

If I understand your question correctly, you're wondering why prop and propTwo are not set in myBar when you've declared Bar to be a subclass of Foo.

The answer is that the constructor function does not automatically call the constructor of its prototype. I think what you probably want is this:

// parent class
function Foo(par){
    this.prop = par;
    this.propTwo = par;
}

// subclass
function Bar(par){
    Foo.call(this, par);  // invoke parent class constructor
    this.p = par;         // custom construction
}
Bar.prototype = new Foo()

As Bergi points out in the comments below, subclassing by setting the subclass's prototype to a new instance of the parent class is probably what you want: that makes all subtype instances inherit from an instance of the parent class, not the parent class's prototype. If you're looking to emulate classical inheritance, your best bet is to the use the Object.create method:

Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;

See the MDN documentation on Object.create for more information. You also might want to read the link Bergi mentioned, and this SO question.

OTHER TIPS

You need to call the Foo function in "context" (or scope) of Bar. The effect is like calling Foo as a parent constructor.

function Foo(par){
        this.prop= par;
        this.propTwo = par;
    }
function Bar(par){
        this.p=par;
        Foo.apply(this,arguments);
    }
Bar.prototype = new Foo();

var myBar = new Bar("value");

console.log(myBar);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top