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.