Reputation: 279
I've been trying to figure out why this won't work. Would appreciate if some could help me out!
function Person(name, age) {
this.name = name;
this.age = age;
var ageInTenYears = age + 10;
this.sayNameAndAge = function() {
console.log(name + age);
}
}
Person.prototype.sayAge = function() {
console.log(this.age);
}
Person.prototype = {
sayName : function(){
console.log(this.name);
},
sayNameAfterTimeOut : function(time) {
setTimeout(this.sayName, time);
},
sayAgeInTenYears : function() {
console.log(ageInTenYears);
}
}
var bob = new Person('bob', 30);
bob.sayName();
I get this error:
Uncaught TypeError: Object #<Object> has no method 'sayAge'
Upvotes: 1
Views: 85
Reputation: 39250
There are several things wrong with the code, I made some comments where I corrected it. If you have any questions you can comment on this answer:
function Person(name, age) {
this.name = name;
this.age = age;
//var ageInTenYears = age + 10; //<--Why var, you can't
// use this anywhere but in the Person constuctor body
this.ageInTenYears=age+10;
}
Person.prototype = {
sayName : function(){
console.log(this.name);
},
sayNameAfterTimeOut : function(time) {
// check out this link about what this can be
// https://stackoverflow.com/a/19068438/1641941
var me=this;
setTimeout(function(){
me.sayName();
}, time);
},
sayAgeInTenYears : function() {
// you defined it as var so cannot use
// ageInTenYears outside the constructor body
//console.log(ageInTenYears);
console.log(this.ageInTenYears);
}
};
Person.prototype.sayAge = function() {
console.log(this.age);
};
Person.prototype.sayNameAndAge = function() {
console.log(this.name + this.age);
};
//just for good measure, someone may do
// Person.prototype.haveBaby=function(){
// return new this.constructor();
Person.prototype.constructor=Person;
var bob = new Person('bob', 30);
bob.sayName();
More on prototype, inheritance/mixin, overriding and calling super: https://stackoverflow.com/a/16063711/1641941
Upvotes: 0
Reputation: 185883
With Person.prototype = { … };
, you're rewriting the prototype
object, i.e. replacing the old one with a completely new object. Cou can do that, but then make sure that you're not defining any methods beforehand (like you do with .sayAge
above).
Upvotes: 3
Reputation: 20033
You are overwriting the entire prototype by doing
Person.prototype = { /* ... */ };
which means that the sayAge
method you added before is lost again. Either reverse the order of those assignments or move the sayAge
into the other assignment as well.
Upvotes: 6