新方法没有看到“这个”(JavaScript)

时间:2016-07-13 06:11:15

标签: javascript oop object methods this

制作一个接受新方法的计算器。但是当我添加一个新方法时,它看不到对象的“这个”。为什么Console.log返回“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["/"]);

2 个答案:

答案 0 :(得分:4)

在尝试调用函数之前,您没有定义this.numberOnethis.numberTwo。此外,您正在打印从未在代码中定义的this.one

如果您尝试了以下代码段:



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["/"]);




然后代码将按预期工作,因为calc.numberOnecalc.numberTwo已定义

答案 1 :(得分:0)

您的号码未初始化。

你还用this.one那是什么?你的意思是numberOne

查看下面的工作代码:



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["/"]);