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   
})()

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

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...
2

Defining a variable without var makes it global.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.