修改对象的原型不起作用
Modifying object's prototype not working
我一直在试图弄清楚为什么这不起作用。如果有人可以帮助我,将不胜感激!
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
相关文章:
- Magento Jquery引导程序和原型冲突?导航标签不起作用
- 对象原型在Canvas Game中不起作用
- JavaScript - 为什么设置原型原型不起作用
- Javascript:分配给对象或数组原型会导致括号不起作用
- 修改对象的原型不起作用
- 将js文件从原型迁移到jQuery不起作用
- 原型扩展jQuery在Internet Explorer中不起作用 - “不支持”
- 为什么原型JavaScript在这种情况下不起作用
- Javascript原型继承不起作用
- 通过原型扩展数学对象不起作用
- 原型函数在IE8中不起作用
- 在主干中向原型对象添加值不起作用
- 通过按钮点击调用原型函数不起作用
- 调用函数内部的原型方法不起作用
- javascript原型更改锚点颜色不起作用
- 为什么功能原型在这个小提琴里不起作用
- 多个元素原型不起作用
- 重写对象's构造函数's原型没有;不起作用
- 为什么对Array原型的更改在我的jQuery插件中不起作用
- 从父对象调用原型方法不起作用