I am trying to implement a way to achieve inheritance in JavaScript. First I define the base class, as follows:
function Person(name){
name = name + "!"; //I want to reuse this code for initialization
this.getName = function(){
return name;
};
this.setName = function(_name){
name = _name;
};
};
Then I define the sub class. Happens that I need a way to call the base class constructor. Ideally I would call it from within VipPerson constructor, when I still have a reference for name param. But if I do it from that point it simply does not work and if I try to access getName from base class I get an error that VipPerson has no getName method.
function VipPerson(name, vipLevel){
this.getVipLevel = function(){
return vipLevel;
};
//the line below would not work!
//VipPerson.prototype = new Person(name);
};
VipPerson.prototype = new Person(); //but this would. not ideal IMO
The drawback for me to set the prototype from outside the VipPerson is that I lose any reference to the parameter were passed.
Is there an elegant way to solve this? I would like to have this clean interface:
var foo = new Person("Foo");
console.log(foo.getName());
var bar = new VipPerson("Bar", 100);
console.log(bar.getName()); //error
console.log(bar.getVipLevel());
Have you tried this approach?