在函数内声明的'var'的范围是什么?

mcg*_*raw 0 javascript jquery

有人可能会为我澄清......我已经读过使用保留字'var'创建一个变量会使该变量公开,但如果变量是在函数内创建的,那该怎么办:

$('#timeIn').timepicker({ 'scrollDefaultNow': true });
    $('#timeIn').on('change', function() {
        var numIn = $('#timeIn').timepicker(('getSecondsFromMidnight'));
        var inHours = {
            hours: (numIn/86400)*24,
            getter: function() {return this.hours;}
        };
        timeIn = $('#timeIn').val();
        inArray.push(timeIn);
        events.push(timeIn);
});
Run Code Online (Sandbox Code Playgroud)

在这个例子中,变量numIn和inHours只在onChange方法中已知,对吗?如果是这种情况,全局声明会是什么样子?'timeIn'是全局范围的但没有操作我只返回一个字符串表示.有什么选择可以将可计算的时间作为回报.

Ala*_*ter 10

使用var函数中的单词将其绑定到该函数的作用域.

不使用该单词var使其在所有函数和所有范围中公开

  • 澄清:不使用`var`,将名称绑定到_global object_,它在浏览器中是`window`对象,但在其他环境(例如Node)中可能不同. (3认同)

jba*_*bey 5

JavaScript使用函数作用域 - 每个变量只能在同一函数内或高于它的作用域中看到.

隐式全局变量是在没有首先声明变量的情况下使用变量时发生的变化.在编译语言中,这会导致编译错误,但是javascript默默地将变量声明为全局对象的属性(在浏览器中这是window对象)

$('#timeIn').on('change', function() {
    var numIn; // only available from inside this anonymous handler function
    ... snip ...
    timeIn = $('#timeIn').val(); // this is an implicit global since it has not been declared anywhere
    // an explicit global, for example's sake
    window.someVar = 'foo';
});
Run Code Online (Sandbox Code Playgroud)

使用javascript v1.7,您还可以通过let关键字建立块范围:

let(a = 5, b = 1) {
    // a and b are scoped to this block
    console.log(a+b); // 6
}
console.log(a+b); // error
Run Code Online (Sandbox Code Playgroud)