English 中文(简体)
Issue with scope and closures in JavaScript
原标题:

My question is really more about scope in JavaScript, rather then closures.

Let s take the following code:

var f = function () {
    var n = 0;
    return function () {
        return n++;
    };
}();

console.log(f());
console.log(f());

The above code outputs:

0
1

As you can see from the above code, f (self-invoked) returns a function, creating a closure of n.


So, it works with an anonymous function; thus, I then tried it with a named function:

var f2 = function () {
    return n++;
};

var f = function () {
    var n = 0;
    return f2;
}();

console.log(f2()); // <= [n is not defined]

The above code doesn t work, with the error n is not defined. I assume that this is a scoping issue; but I cannot figure why exactly;

Why is it that the scope is the same with an anonymous, inner function but does not work with a named, outer function?

Also, in the second example, am I creating a closure?

最佳回答

The closure is created in the first example because the code in the anonymous function uses a local variable that is declared outside of the anonymous function.

In the second example the scope of the n variable in the function f2 is already decided when the function is declared. Creating a local variable with the same name doesn t change the meaning of the function, and using the function inside another function doesn t change it s scope. Thus, the function doesn t use the local variable.

问题回答

There is no way for f2 to figure out where it should take variable n.

In first example anonymous function is inside function f, in second - outside (f2 instead of anonymous). So, f2 cannot access variable n, because it is in another scope and inaccessible (invisible). Try put f2 declaration inside f.

In your second example, you are not creating a closure, you are simply returning a global variable. f2 is not being closed over because it was declared in a more general (in this case, global) scope, and n is declared in a more specific scope. Closure is possible down the scope chain "funnel," not up, and is only effective when all related entities are defined in the same scope.

We could rewrite your second example to make it work with a named function:

var f = function() {
    var n = 0;
    var f2 = function() {
        return n++;
    };
    return f2;
}();
console.log(f());
console.log(f());

This would output, 0 and 1 as your first example did.

As the other answers have stated, its not about the function being named or anonymous, its about scope of n and f2. Since you declared f2 outside of f in your example, it had no access to the variable n declared inside the scope of f.





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签