2013-11-03 43 views
1

我一直在試圖弄清楚爲什麼這不起作用。希望如果有人能幫助我!通過做修改對象的原型不起作用

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

這意味着你之前添加的sayAge方法失去了再次

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

回答

7

要覆蓋整個原型:

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

我得到這個錯誤。要麼顛倒這些分配的順序,要麼將sayAge也移動到另一個分配中。

+0

還有其他一些明顯的事情,錯誤的代碼:ageInTenYears不在sayAgeInTenYears中定義(不同於具有未定義的值)。當從sayNameAfterTimeOut調用時,'this'的值是sayName中的窗口,導致this.name的值爲undefined – HMR

3

隨着Person.prototype = { … };,你重寫prototype對象,即用一個完全新的對象換舊人。 Cou可以做到這一點,但是確保你沒有事先定義任何方法(就像你使用上面的.sayAge一樣)。

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

更多關於原型,繼承/混入,覆蓋並調用超:https://stackoverflow.com/a/16063711/1641941