javascript - 为什么我在 Javascript 中收到错误消息对象没有方法?

标签 javascript

我有以下代码但是我收到错误 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/

相关文章:

javascript - 只在顶部添加了1行代码

javascript - 使用 Parse 客户端站点登录 Facebook,使用 Express js 的用户对象

javascript - 解析json文本

javascript - 如何在 JavaScript 中从位图中添加乘法和除法符号?

php - 为什么我的动态表没有过滤?

javascript - meteor : how to make Relationships one to many?

javascript - 在本地和沙盒外部署 Vue 应用程序

JavaScript 库性能比较 - 有什么资源吗?

javascript - 防止在 HTML 中选择

javascript - JavaScript 中同一行的多个比较/赋值运算符