hbrls
hbrls

Reputation: 2150

Why can access the variable in "what-I-think-is-a-closure"?

I have code like this: (and on jsfiddle http://jsfiddle.net/k6zNm/3/)

(function(){
    Marker = function(opts){
        var marker = this;
        marker.Version = "2012.Jul.06";
        marker.HelloWorld = function(){
            return marker.Version;
        }
    }
})();

window.mymarker = new Marker();
$("div#message").text(mymarker.HelloWorld());

The code works fine. But I think the (function(){})(); is a closure. Why can I access the Marker in it. Isn't it a pollution to global namespace?

Upvotes: 0

Views: 99

Answers (4)

Florian Margaine
Florian Margaine

Reputation: 60717

The closure is just the upper scope. For example:

( function() {
    var i = 0;
    ( function() {
        // i is in the closure, the upper scope
    } () );
} () );

Don't forget that javascript's only scope is function scope.

(function(){})(); is an immediately invoked function expression.

But yeah, for your example, the problem is just that you missed the var, so Marker is a global variable.

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Your code is not a closure. A closure is like below, you need to return the function out, note that the variable version is out of your returned function scope.

var Marker = (function(){
    var version = "2012.Jul.06";
    return function(opts){
        var marker = this;
        marker.Version = version;
        marker.HelloWorld = function(){
            return marker.Version;
        };
    };
})();

You could access Marker is just because it is a global variable in your code.

Upvotes: 1

Quentin
Quentin

Reputation: 943214

You haven't used var with Marker, so it is a global variable instead of being scoped to the function.

Upvotes: 5

Ankur
Ankur

Reputation: 33637

Because you haven't put var in front of Marker, thats why it get created in global level.

Upvotes: 0

Related Questions