I asked Bing AI:
in javascript, how to access outer object’s this from inner objects function ?
The answer starts with:
To access the outer object’s
this
from an inner object’s function in JavaScript, you can assign the outer object’sthis
to a local variable and use that variable inside the inner object’s function. Here is an example:
var outerObject = { outerProperty: 'outerPropertyValue', innerObject: { innerFunction: function() { console.log(outerObject.outerProperty); } } }; outerObject.innerObject.innerFunction(); // logs 'outerPropertyValue'
To name the outer object - not a bad idea at all, only it was not applicable for me.
But then, there was more:
You can also use arrow functions in ES6 to capture the
this
value of the enclosing context, avoiding the need to assignthis
to a new variable or to use bound functions. Here is an example:
var outerObject = { outerProperty: 'outerPropertyValue', innerObject: { innerFunction: () => { console.log(this.outerProperty); } } }; outerObject.innerObject.innerFunction(); // logs 'outerPropertyValue'
That looks nice and simple!
But, isn’t innerFunction
’s this
the innerObject
? 🤔
Running the code produces an expected undefined
.
So, nothing new - AI offers convincing anwers which are wrong - it’s only that it happened to me for the first time.