JS 从此对象内的嵌套对象调用函数

JS Calling functions from a nested object inside this object

实际上我正在尝试 运行 以下代码:

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

myObj.subObj.methodA('Hello World');
我收到错误 "Uncaught TypeError: this.methodB is not a function"。

为什么我会收到这个错误? "methodB" 不是通过 'this' 在 methodA 的范围内吗?

非常感谢

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

箭头函数有特殊的绑定。箭头函数中 this 的值等同于函数定义处(词法范围)的 this 的值。在这种情况下 window(在浏览器中)。要使您的函数正常工作,请使用 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');

关于此的更多信息是 explained here

箭头函数没有单独的 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');

Since normal functions use this of the caller and you call methodA as myObj.subObj.methodA, this = myObj.subObj. Hence this.methodB is available as it's equivalent to myObj.subObj.methodB