5

我在一个文件中有以下代码:

function refreshGridSuccess(responseText, entity) {

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

在另一个文件中,我有:

$('#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;
        })

oTable除了这里,我没有定义。脚本似乎可以工作,这是否意味着它oTable以某种方式变成了全局变量?

现在我正在尝试开始使用 Typescript,如果没有Otable声明它就不会接受。有没有一种方法可以声明oTable为对象,还是必须将其声明为与返回的类型相同的对象$('#dataTable').dataTable({})

4

3 回答 3

3

如果您在全局范围内,则没有区别。如果你在一个函数中,那么“var”将创建一个局部变量,“no var”将查找作用域链,直到找到变量或到达全局作用域(此时它将创建它)。

在这里找到:var 关键字的用途是什么以及何时使用它(或省略它)?

于 2012-11-11T07:23:34.573 回答
2

是的,未使用 var 声明的变量将变为全局变量。在函数范围之外使用时,不一定需要,但是,使用在函数中定义的全局定义变量会导致不可预测的结果。

“在这些情况下未能声明变量很可能会导致意外结果。因此,在 ECMAScript 5 严格模式下,为函数内未声明的变量赋值会引发错误。” - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var

于 2012-11-11T07:23:41.553 回答
2

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?

于 2012-11-11T07:25:44.463 回答