修改对象的原型不起作用

Modifying object's prototype not working

本文关键字:不起作用 原型 对象 修改      更新时间:2023-09-26

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

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' 

你正在通过

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

这意味着您之前添加的sayAge方法再次丢失。要么反转这些分配的顺序,要么将sayAge移动到其他分配中。

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

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

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

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