Javascript nested function losing scope

好久不见. 提交于 2020-01-01 12:11:12

问题


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 ?


回答1:


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);



回答2:


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);



回答3:


window.name = "window";

object = {
    name: "object",
    method: function () {
        var self = this;
        var nestedMethod = function () {
            console.log(self.name); // or object.name without declaring self
        }
        nestedMethod();
    }
}

object.method(); // print 'object'

Save the scope of the object - or use the object itself!

do all the anonymous functions that we created will go on the global scope ?

No, not all the anonymous functions lose their scope, all the functions scopes are bound to the global object(if they are not called with specific this, see apply and call, see the example below)!

window.name = "window";

object = {
    name: "object",
    method: function () {
        var nestedMethod = function () {
            console.log(this.name);
        }
        nestedMethod.call(this); //change the this arg in the current object scope
        // when you call this function with .call(this) you are changing the value of the nestedMethod's this to the current this, which is object
    }
}

object.method(); // print 'object'


来源:https://stackoverflow.com/questions/17558635/javascript-nested-function-losing-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!