I’ve been trying to learn OO style JS today, but am having an issue with inheritance. I have the following, which seems to work okay, and is hopefully correct:
function Person(name){
var job; //private
this.name=name; //public
}
Person.prototype.setJob=function(jobb){
job=jobb;
}
Person.prototype.getJob=function(){
return job;
}
Person.prototype.getName=function(){
return this.name;
}
function Postman(name){
//construct the parent
Person.call(this, name);
//set the job on the parent
//this.setJob('Postman');
job="Postman";
}
//Postman extends Person
Postman.prototype=new Person();
Postman.prototype.parent=Person.prototype;
//Postman constructor will be Person now, so switch it back to Postman
Postman.prototype.constructor=Postman;
//Override the parent method
Postman.prototype.getName=function(){
//call the parent method to get the name
return this.getJob()+" "+this.parent.getName.call(this);
};
var MrsGoggins = new Person('Mrs Goggins');
MrsGoggins.setJob('Shop assistant');
console.log(MrsGoggins.getJob()); //Shop assistant
console.log(MrsGoggins.getName()); //Mrs Goggins
var Pat = new Postman('Pat');
console.log(Pat.getJob()); //Postman
console.log(Pat.getName()); //Postman Pat
The issue is, if I modify the Person object so that name is required e.g.
function Person(name){
var job; //private
if(!name){
throw {"name" : "InvalidArgument", "message" : "name of Person must be supplied", "toString" : function(){return this.name+": "+this.message}};
}
this.name=name; //public
}
Then when the script gets to Postman.prototype=new Person(); the error will be thrown as no name is supplied.
So, I’m not sure how you are meant to extend an object if that object requires a parameter to be instantiated?