简体   繁体   中英

Does a JavaScript variable not declared with var become global?

I have the following code in one file:

function refreshGridSuccess(responseText, entity) {

    oTable = $('#dataTable').dataTable({
        "sScrollX": "100%",

In another file I have:

$('#detailData')
        .on('click', '.sort-up', function (event) {
            event.preventDefault();
            var column = $(this).closest('th'),
                columnIndex = column.parent().children().index(column.get(0));
            oTable.fnSort([[columnIndex, 'asc']]);
            return false;
        })

I have no definition for oTable except here. The scripts seem to work so does that mean that oTable was somehow made into a global variable?

Now I am trying to start using Typescript and it will not accept Otable without it being declared. Is there a way I can declare oTable as an object or do I have to declare it as an object to be the same type as is returned by $('#dataTable').dataTable({}) ?

If you're in the global scope then there's no difference. If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).

Found here: What is the purpose of the var keyword and when to use it (or omit it)?

Yes, a variable not declared with var becomes global. When used outside of a function's scope it is not necessarily required, however, using a globally defined variable which was defined in a function results in unpredictable results.

"Failure to declare the variable in these cases will very likely lead to unexpected results. For that reason, in ECMAScript 5 strict mode, assigning a value an undeclared variable inside a function throws an error." - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var

You are correct. Variable without a var declaration is treated as global. If you are in a browser, that scope is window

Also note that Javascript variables are function-scoped. Meaning if you have a code like this:

function test()
{
   for (var key in someObject)
   {
      var foo = 'bar';
   }
}

It is equivalent to this:

function test()
{
   var foo, key;
   for (key in someObject)
   {
      foo = 'bar';
   }
}

It doesn't matter which block the var declaration is placed in, the actual declaration happens at the beginning of the function. This is also called variable hoisting if you want to google it.

Now about Typescript , I haven't had a chance to play with it. But I assume you can still do var oTable; right before you use the variable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM