简体   繁体   English

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

[英]Why do I get the error message Object has no method in Javascript?

I have the following code however am getting the error Uncaught TypeError: Object #<addThis> has no method 'returnValue' (anonymous function) 我有以下代码但是得到错误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());

when you use this. 当你使用this. it is public in scope. 它的范围是公开的。 when you use var , it is private . 当你使用var ,它是私有的 since you used var returnValue , it is private, and thus not exposed for use. 因为你使用了var returnValue ,所以它是私有的,因此不会暴露使用。

In fact, i'm guessing you wanted to hide the values and expose the getter, so reverse what you did.. 事实上,我猜你想要隐藏价值并暴露吸气剂,所以要扭转你的所作所为......

function addThis() {
    var value1 = 1;
    var value2 = 2;

    this.returnValue = function () {
        return (this.value1 + this.value2);
    }
}

var will declare a variable local to the function. var将声明函数的本地变量。 I think you meant to assign it to this.returnValue : 我想你打算把它分配给this.returnValue

function addThis() {
    this.value1 = 1;
    this.value2 = 2;

    this.returnValue = function () {
        return (this.value1 + this.value2);
    };
}

// Instantiate object and write response
var simpleObject = new addThis();
document.write(simpleObject.returnValue());

Because returnValue is just a local variable in the addThis function, it doesn't end up in the object that is created. 因为returnValue只是addThis函数中的局部变量,所以它不会在创建的对象中结束。

Assign the function to a property of the object: 将函数分配给对象的属性:

function addThis() {
  this.value1 = 1;
  this.value2 = 2;

  this.returnValue = function() {
    return this.value1 + this.value2;
  };
}

Or use the prototype for the object: 或者使用原型作为对象:

function addThis() {
  this.value1 = 1;
  this.value2 = 2;
}

addThis.prototype.returnValue = function() {
  return this.value1 + this.value2;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM