Alexey Tseitlin
Alexey Tseitlin

Reputation: 1319

New method does not see "this" (JavaScript)

Making a calculator that accepts new methods. But when I add a new method it does not see object's "this". Why Console.log returns "undefined"?

function Calculator() {
  this.numbers = function() {
      this.numberOne = 2;
      this.numberTwo = 5;
    },
    this.addMethod = function(op, func) {
      this[op] = func(this.numberOne, this.numberTwo);

    // WHY LOG RETURNS "undefined"?
      console.log(this.numberOne);
    }
}

let calc = new Calculator();

calc.addMethod("/", (a, b) => (a / b));
document.write(calc["/"]);

Upvotes: 1

Views: 77

Answers (2)

ahitt6345
ahitt6345

Reputation: 510

You did not define this.numberOne and this.numberTwo before you tried to call the function on it. Moreover, you are printing this.one which is never defined in your code.

If you tried the following snippet:

function Calculator() {
  this.numbers = function() {
    this.numberOne = 2;
    this.numberTwo = 5;
  },
    this.addMethod = function(op, func) {
    this[op] = func(this.numberOne, this.numberTwo);

    // WHY LOG RETURNS "undefined"?
    console.log(this.numberOne);
  }
}

let calc = new Calculator();
calc.numbers();
calc.addMethod("/", (a, b) => (a / b)); // 2/5
document.write(calc["/"]);

Then the code will work as expected because calc.numberOne and calc.numberTwo are defined

Upvotes: 4

hityagi
hityagi

Reputation: 5256

Your numbers were not getting initialized.

Also you used this.one what's that? Did you mean numberOne.

Check out the working code below :

function Calculator() {
  this.numberOne = 2;
  this.numberTwo = 5;
  this.addMethod = function(op, func) {
    this[op] = func(this.numberOne, this.numberTwo);
    // WHY LOG RETURNS "undefined"?
    console.log(this.numberOne, this.numberTwo );
  }
}

let calc = new Calculator();
calc.addMethod("/", (a, b) => (a / b));
document.write(calc["/"]);

Upvotes: 0

Related Questions