Question

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' 
Was it helpful?

Solution

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.

OTHER TIPS

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).

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top