Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript question: about variable definition

Tags:

javascript

I have no idea why it didn't work if I specify a variable with 'var': like this:

var mytool = function(){
      return {
         method: function(){}
     }
}();

And later I use it in the same template: mytool.method. This will output mytool was not defined.

But if I define it like this:

     mytool = function(){
          return {
             method: function(){}
         }
    }();

Then it works.

like image 518
Joshua Avatar asked Dec 19 '25 04:12

Joshua


1 Answers

Javascript has function scope. A variable is in scope within the function it was declared in, which also includes any functions you may define within that function.

function () {
    var x;

    function () {
        // x is in scope here
        x = 42;

        y = 'foo';
    }

    // x is in scope here
}

// x is out of scope here

// y is in scope here

When declaring a variable, you use the var keyword.
If you don't use the var keyword, Javascript will traverse up the scope chain, expecting to find the variable declared somewhere in a higher function. That's why the x = 42 assignment above assigns to the x that was declared with var x one level higher.

If you did not declare the variable at all before, Javascript will traverse all the way to the global object and make that variable there for you. The y variable above got attached to the global object as window.y and is therefore in scope outside the function is was declared in.
This is bad and you need to avoid it. Properly declare variables in the right scope, using var.

like image 177
deceze Avatar answered Dec 20 '25 20:12

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!