actually im trying to run the following code:
var myObj = {
subObj: {
methodA: (parA) => {
this.methodB(parA); //This is not working
},
methodB: (parB) => {
console.log(parB);
}
}
}
myObj.subObj.methodA('Hello World');
Why am i getting this error? Isn't "methodB" in scope of methodA via 'this'?
Thank you very much
Arrow functions don't have separate this.
Hence doing
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
is similar to doing:
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.
In the latter's case, things will work when you do the following:
myObj.subObj.methodA('Hello World');
Since normal functions use
this
of the caller and you callmethodA
asmyObj.subObj.methodA
,this
=myObj.subObj
. Hencethis.methodB
is available as it's equivalent tomyObj.subObj.methodB