开发者

Why closure in ajax call has access to the outer scope?

I read about JavaScript closures and I thought that I understood it, but apparently I didn't.

The success function is called when request is succeeded. This means that when the closure (function () { return obj; })(); is executed the scope, inside success function, is NOT function (evt) {...} anymore, so how it can still access obj?

How the closure work in this example

EDITED(there is var before obj)

function (evt) {
           var obj = evt.data.obj,
            $.ajax({
                type: "POST",
                url: url,
                data: data,
               开发者_C百科 success: function () {
                    var o = (function () {
                        return obj;
                    })();
                }                    
            });
}


In JS, scope is limited by function.

Everything inside a function to which a variable is scoped can access that variable — including other functions — unless there is another variable of the same name in a narrower scope.

That said, in this example there is no var keyword to localise the scope of the obj anyway, so it is a global. Removed after edit of question


One way to look at it is that closures have access to all scopes above themselves.

Another way would be to say that obj actually is accessible in scope of function function(evt), which is parent to the scope of function(), and therefore, obj is also accessible from function().

Either way, this is how JavaScript works: closure has access to everything that is accessible at the closure's point of definition.


A closure has access to all higher scopes, not only the "parent scope".


Since an obj variable isn't defined in the current scope, JavaScript goes up all the scopes the function has access to until it finds it.

It's like someone looking up a very weird ladder; one which can split to sub-ladders, but when you climb down these sub-ladders, you are still in the bigger ladder.


A closure has by design access to surrounding scope upon creation as it is created within the scope.

Any variables you access in the outer scope is accessed through a reference that will keep the variable alive after the scope within which it was created is destroyed.

That way when the closure executes, the variables it was referencing will still exist and only after the closure is disposed will the variables be released.


Each Function object has an Activation object that represents it's execution context.
Within a group of nested functions, A scope chain is formed starting from the inner most Activation object and ending with the Global object (Global Scope).
So unless there's a name clash between variables ,Each function has access to all of it's parent functions' local variables and parameters in addition to global variables.
Here's a lengthy but very useful explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜