i written a simple javascript inheritance prototype, but i am getting issue.. any one guide me the correct declaration?
code:
var Man = function(params){
this.name = params.name,
this.age = params.age,
this.job = params.job;
}
Man.prototype.work = function(){
return this.name +' is working as a ' + this.job;
}
var Women = function(params){
this.name = params.name,
this.age = params.age,
this.job = params.job;
}
Women.prototype = new Man(); //assigning the prototype
var man1 = new Man({name:'man1',age:'age1',job:'job1'});
console.log(man1.work()); //it works
var woman1 = new Women({name:'woman1',age:'age2',job:'job2'});
console.log(woman1.work()); // it is not.. why?
the error i am getting :
TypeError: params is undefined
[Break On This Error]
this.name = params.name,
2 Answers 2
You are getting this error because you are calling Man without any arguments:
Women.prototype = new Man();
Since inside the function, params is undefined, accessing params.name will raise an exception.
That's one of the reasons why setting the prototype like this is inconvenient. You don't really want to create a new instance of Man at this moment, you only want to hook up its prototype into the prototype chain.
Better use Object.create [MDN] (includes polyfill) to create an object with a specific prototype:
Women.prototype = Object.create(Man.prototype);
Women.prototype.constructor = Women;
and inside Women, call the parent constructor (it's not meant to be a dirty joke) to pass along the arguments:
function Women(params) {
Man.call(this, params);
}
2 Comments
create method: IE9+, FF4+You're not passing your parameters from the woman to the man, try this:
Women.prototype = new Man({name:this.name,age:this.age,job:this.job});
Actually, this would work also:
Women.prototype = new Man(this);
The advantage is that it's just 4 letters of extra code, and this should work on all browsers that support JS.
10 Comments
Work is a function in the prototype of Man. It can't "see" the variables passed to Women, you'll have to pass it along.this will refer to window... it might "work" but it is very unintuitive design.this refers to window. The reason why you still get the correct output is because you are shadowing name, age and job through the Women constructor. The only reason it works is because you are passing an object to Man. Women.prototype = new Man({}); would work just as well. Have a look at the prototype chain: jsfiddle.net/QkjwB/1.Women.prototype = new Man(this);, you did not even create a Women instance yet (you did not call new Women and passed any parameters to it). this cannot refer to the Women instance at this point.
Women.prototype = new Man();is a bad way of of setting the prototype.vardeclaration.