Im reading "Eloquent Javascript" book and I'm in the chapter "The secret life of objects". And the author says:
"since each function has it's own bindings, whose value depends on they way it is called, you cannot refer to the
thisof the wrapping scope in a regular function defined with thefunctionkeyword.
i did not understand what does he mean by "wrapping scope", can you please explain and provide a simple example?
Wrapping scope of your function would be the scope where the function is defined. e.g.
function outer() {
var outerThis = this;
return function inner() {
console.log(outerThis, this);
}
}
Here, inner function has wrapping scope = scope of outer. And, the inner function doesn't have access to the outer's this which is why we need to store it in a variable outerThis if we want to use it.
var innerFunction = outer.call({});
innerFunction();
If you do above on chrome console, This will print:
{}, // Caller of outer() (it was bound)
Window // Caller of inner()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With