我一直试图弄清楚为什么这不起作用。如果有人可以帮助我,我将不胜感激!
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'
答案 0 :(得分:7)
您正在通过
覆盖整个原型Person.prototype = { /* ... */ };
表示您之前添加的sayAge
方法再次丢失。要么颠倒这些作业的顺序,要么将sayAge
移到另一个作业中。
答案 1 :(得分:3)
使用Person.prototype = { … };
,您将重写prototype
对象,即用一个全新的对象替换旧对象。 Cou可以做到这一点,但确保你事先没有定义任何方法(就像你上面的.sayAge
一样)。
答案 2 :(得分: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