【问题标题】:Can someone please explain why `this` is different in these two cases [duplicate]有人可以解释为什么在这两种情况下`this`不同[重复]
【发布时间】:2021-11-12 10:25:23
【问题描述】:
let obj = {
    one: function(){
        this.two();
    },

    two: function(){
        console.log("two");
    }
}

let oneFunc = obj.one;

obj.one(); // two

oneFunc(); // TypeError: this.two is not a function

我用 JavaScript 编程已经有一段时间了。我以为我对 this 关键字有一个非常扎实的把握。然而,我今天遇到了这个问题,这让我大吃一惊。我无法弄清楚为什么会这样。当我调用oneFunc() 时,this 指的是全局对象。为什么会这样?

【问题讨论】:

  • 因为this 取决于调用函数的人以及调用方式。
  • this 指的是调用函数的对象

标签: javascript node.js this


【解决方案1】:

this 引用对象,而您在这里所做的是创建一个等于对象方法的函数,因此您失去了对对象的引用。

你可以使用绑定

let obj = {
    one: function(){
        this.two();
    },

    two: function(){
        console.log("two");
    }
}

let oneFunc = obj.one;
oneFunc = oneFunc.bind(obj);

obj.one(); // two

oneFunc(); // TypeError: this.two is not a function

【讨论】:

  • 这实际上很有意义。不过看起来还是很奇怪。我很惊讶我以前没有遇到过这个问题。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
相关资源
最近更新 更多