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ます。つまり、古いオブジェクトを完全に新しいオブジェクトに置き換えます。それはできますが、事前にメソッドを定義していないことを確認してください(.sayAge上記のように)。

于 2013-11-03T15:13:33.090 に答える