Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript nested function losing scope

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 ?

like image 544
peter Avatar asked Mar 24 '23 05:03

peter


2 Answers

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);
like image 95
basilikum Avatar answered Apr 02 '23 13:04

basilikum


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);
like image 25
Pointy Avatar answered Apr 02 '23 14:04

Pointy