Javascript question: variable definition

I have no idea why this did not work if I specify a variable with 'var': for example:

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

And later I use it in the same template: mytool.method. This will result in the output mytool has not been determined.

But if I define it like this:

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

Then it works.

+3
source share
4 answers

Javascript has a scope. The variable is in scope within the function in which it was declared, which also includes any functions that you can define inside this 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

var.
var, Javascript , , - . x = 42 x, var x .

, Javascript . y window.y , , ​​.
, . , var.

+5

, , . var "", (javascript ). var , , . , , .

+2

, :

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

mytool ; setup_mytool , .

window.mytool window.my_global_collection.mytool mytool .

:

var mytool;

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

, , , .

+2

, undefined, , var , , (, , whathaveyou).

var, , , . ( ).

, , mytool - , , , var - , .

+1

Source: https://habr.com/ru/post/1777609/


All Articles