【问题标题】:why using 'this' keyword not working while it's working with object name [duplicate]为什么在使用对象名称时使用“this”关键字不起作用[重复]
【发布时间】:2021-01-19 12:29:14
【问题描述】:

使用“计算器”调用函数时,我在控制台得到结果,但使用“this”关键字时显示未定义

const calculator = {
  calcBMI: function (mass, height) {
    const BMI = mass / height ** 2;
    return BMI;
  },
  firstName: "Arvind",
};

console.log(calculator.calcBMI(6, 1.8));
console.log(this.calcBMI(6, 1.8));

【问题讨论】:

  • this 将不等于 calculator。实际值将取决于上下文和执行,但至少在您显示的代码中可能是windowundefined
  • 我完全不知道为什么你会期望 this 在给定代码的情况下解析分配给 calculator 的对象。

标签: javascript this


【解决方案1】:

这里this代表窗口对象。窗口对象中没有定义calcBMI 方法。所以它返回undefined

const calculator = {
  calcBMI: function(mass, height) {
    const BMI = mass / height ** 2;
    return BMI;
  },
  firstName: "Arvind",
};

console.log(this)

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2015-11-28
    • 1970-01-01
    • 2010-10-25
    • 2011-01-26
    • 1970-01-01
    相关资源
    最近更新 更多