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.