Can someone explains the scope binding of the following code please
window.name = "window";
object = {
name: "object",
method: function() {
nestedMethod: function() {
console.log(this.name);
}
nestedMethod();
}
}
object.method(); // print 'window'
I think my question is more about this
...why is this
losing the scope and default to the global scope ? do all the anonymous functions that we created will go on the global scope ?
Whenever you call a function, simply by writing func()
, this
inside the function will point to the global object. In your case you write:
nestedMethod();
So this
inside nestedMethod
is the window object. You can use call
(or apply
) to manually define a context for you function call:
nestedMethod.call(this);
Any function that's invoked like this:
someFunction();
will have the global scope as the value of this
(in non-strict mode). You can either stash the outer scope in a local variable, or else use .call()
or .apply()
:
nestedMethod.call(this);
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