1

实际上我试图运行以下代码:

var myObj = {
  subObj: {
    methodA: (parA) => {
      this.methodB(parA); //This is not working
    },
    methodB: (parB) => {
      console.log(parB);
    }
  }
}

myObj.subObj.methodA('Hello World');
我收到错误“未捕获的 TypeError:this.methodB 不是函数”。

为什么我会收到此错误?“methodB”不是通过“this”在methodA的范围内吗?

非常感谢你

4

3 回答 3

1

箭头函数具有特殊绑定。in 箭头函数的值this等价于定义函数的 this 的值(词法范围)。在这种情况下窗口(在浏览器中)。要使您的函数正常工作,请使用this引用封闭上下文的常规函数​​:

var myObj = {
  subObj: {
    methodA: function (parA) {
      this.methodB(parA); //This is not working
    },
    methodB: function (parB) {
      console.log(parB);
    }
  }
}

myObj.subObj.methodA('Hello World');

更多关于此的解释here

于 2020-06-06T19:28:32.123 回答
1

箭头函数没有单独的this

因此做

var myObj = {
  subObj: {
    methodA: (parA) => {
      this.methodB(parA); // `this` will always be window / outer context as arrow functions will not bind `this` at runtime.
    },
    methodB: (parB) => {
      console.log(parB);
    }
  }
}


myObj.subObj.methodA('Hello World'); // fails as `this.methodB` in your `methodA` is equivalent to `window.methodB` which is not present

类似于做:

var myObj = {
  subObj: {
    methodA: function(parA) {
      this.methodB(parA);
    },
    methodB: function(parB) {
      console.log(parB);
    }
  }
}

myObj.subObj.methodA.call(window || {}, 'Hello World');  // where window || {} is the lexical / outer scope to your function.

在后者的情况下,当您执行以下操作时,事情会起作用:

myObj.subObj.methodA('Hello World');

由于普通函数使用this调用者并且您调用methodAas myObj.subObj.methodA, this= myObj.subObj。因此this.methodB可用,因为它相当于myObj.subObj.methodB

于 2020-06-06T19:44:18.303 回答
0

我的猜测是,这是因为所有这些都是匿名的、非范围的、非实例化的对象,this实际上是指窗口对象。

于 2020-06-06T19:18:16.293 回答