Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding the "this" binding

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 this of the wrapping scope in a regular function defined with the function keyword.

i did not understand what does he mean by "wrapping scope", can you please explain and provide a simple example?

like image 264
Abdelellah Dandashi Avatar asked Sep 05 '26 02:09

Abdelellah Dandashi


1 Answers

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()
like image 153
chiragrtr Avatar answered Sep 10 '26 21:09

chiragrtr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!