views:

76

answers:

4

I was wondering why the Vector variable defined within this self executing javascript function doesn't require a var before it? Is this just some other type of syntax for creating a named function? Does this make it so we can't pass Vector as an argument to other functions?

(function() {
    Vector = function(x, y) {
        this.x = x;
        this.y = y;

        return this;
    };

   //...snip   
})()
+2  A: 

Defining a variable without var makes it global.

mkj
+3  A: 

The code construct above makes Vector a global variable in the namespace, which might be OK since it is probably intended to be used as constructor.

I would not recommend adding to the global name space, actually take a look at requirejs its a very nice way to work with modular JS.

Ernelli
+1  A: 

Vector in this case will be attached to the current this which would be window. At least in the code you presented, there doesn't seem to be a need for the enclosing self executing function.

Eric Strom
+2  A: 

Defining Vector any other way would only create it within the scope of the closure; and would not be available outside the closure.

(function() {
    var Vector = function(x, y) {
        this.x = x;
        this.y = y;

        return this;
    };

    function Vector() {
        // blah
    };

   //...snip   
})()

var something = new Vector() // ERROR :<

Nothing "requires" the var keyword; using it defines the scope the variable is available within. Not using it means the variable is created in the global scope.

Matt
Thanks for the help everyone. Probably more an issue with VS2008 JS intellisense; but for some reason, Vector isn't showing up outside the self executing function...
Pierreten