1

我一直在试图弄清楚为什么这不起作用。如果有人可以帮助我,将不胜感激!

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();

我收到此错误:

  Uncaught TypeError: Object #<Object> has no method 'sayAge' 
4

3 回答 3

6

您正在通过执行覆盖整个原型

Person.prototype = { /* ... */ };

这意味着sayAge你之前添加的方法又丢失了。要么颠倒这些分配的顺序,要么也将它们移动sayAge到另一个分配中。

于 2013-11-03T15:13:22.937 回答
3

使用Person.prototype = { … };,您正在重写prototype对象,即将旧对象替换为全新对象。Cou 可以这样做,但要确保您没有事先定义任何方法(就像您在.sayAge上面所做的那样)。

于 2013-11-03T15:13:33.090 回答
0

代码有几个问题,我在更正的地方做了一些评论。如果您有任何问题,您可以对此答案发表评论:

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();

更多关于原型、继承/混合、覆盖和调用 super:https ://stackoverflow.com/a/16063711/1641941

于 2013-11-03T15:37:13.517 回答