箭头函数没有单独的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
调用者并且您调用methodA
as myObj.subObj.methodA
, this
= myObj.subObj
。因此this.methodB
可用,因为它相当于myObj.subObj.methodB