简体   繁体   中英

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)

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. it is public in scope. when you use var , it is private . since you used var returnValue , it is private, and thus not exposed for use.

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. I think you meant to assign it to this.returnValue :

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

    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.

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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