我有以下代码但是我收到错误 Uncaught TypeError: Object #<addThis> has no method 'returnValue' (anonymous function)
function addThis() {
this.value1 = 1;
this.value2 = 2;
var returnValue = function () {
return (this.value1 + this.value2);
}
}
//Instantiate object and write response
var simpleObject = new addThis();
document.write(simpleObject.returnValue());
最佳答案
因为 returnValue
只是 addThis
函数中的局部变量,所以它不会在创建的对象中结束。
将函数分配给对象的属性:
function addThis() {
this.value1 = 1;
this.value2 = 2;
this.returnValue = function() {
return this.value1 + this.value2;
};
}
或者使用对象的原型(prototype):
function addThis() {
this.value1 = 1;
this.value2 = 2;
}
addThis.prototype.returnValue = function() {
return this.value1 + this.value2;
};
关于javascript - 为什么我在 Javascript 中收到错误消息对象没有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11217442/