修改对象的原型不起作用

The*_*ppe 1 javascript prototype prototype-programming

我一直试图找出为什么这不起作用.如果有人可以帮助我,我将不胜感激!

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();
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

  Uncaught TypeError: Object #<Object> has no method 'sayAge' 
Run Code Online (Sandbox Code Playgroud)

Ing*_*ürk 6

你正在覆盖整个原型

Person.prototype = { /* ... */ };
Run Code Online (Sandbox Code Playgroud)

这意味着sayAge您之前添加的方法会再次丢失.要么颠倒那些作业的顺序,要么也sayAge进入另一个作业.