Theo Felippe
Theo Felippe

Reputation: 279

Modifying object's prototype not working

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

Answers (3)

HMR
HMR

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

Šime Vidas
Šime Vidas

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

Ingo B&#252;rk
Ingo B&#252;rk

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

Related Questions