【问题标题】:New method does not see "this" (JavaScript)新方法看不到“this”(JavaScript)
【发布时间】:2016-11-15 13:54:18
【问题描述】:

制作一个接受新方法的计算器。但是当我添加一个新方法时,它看不到对象的“this”。为什么 Console.log 返回“未定义”?

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

【问题讨论】:

  • 第 5 行有错字:逗号应该是分号。
  • this.one 从未设置,所以是的,它是undefined
  • +goliadkin 我认为无论哪种方式都可以...

标签: javascript oop object methods this


【解决方案1】:

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

如果您尝试了以下 sn-p:

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

【讨论】:

  • this.one 是一个错字。使用 calc.numbers();一切正常!非常感谢!
【解决方案2】:

您的号码未初始化。

您还使用了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["/"]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2012-06-30
    • 2011-04-01
    • 2013-02-16
    相关资源
    最近更新 更多