可变范围和qUnit测试

Variable scope and testing with qUnit

本文关键字:qUnit 测试 范围      更新时间:2023-09-26

我是qUnit测试的新手,很难理解为什么我的变量"a"通过了范围测试,即使在定义"a"之前调用了测试。当我注销"a"时,它的行为与预期的一样。有人能给我一个提示吗?

这是代码:

function outer() {
    test('inside outer', function (assert) {
        assert.equal(typeof inner, "function", "inner is in scope"); //pass
        assert.equal(typeof a, "number", "a is in scope"); // pass
    });
    console.log(a); // undefined
    var a = 1;
    console.log(a); // 1
    function inner() {}
    var b = 2;
    if (a == 1) {
        var c = 3;
    }
}
outer();

由于JavaScript的提升,"a"实际上是在函数的顶部声明的,但在代码中为其赋值的地方初始化。

所以,当你的代码被解释时,它实际上看起来更像这样:

function outer() {
    var a, b, c;
    test('inside outer', function (assert) {
        assert.equal(typeof inner, "function", "inner is in scope"); //pass
        assert.equal(typeof a, "number", "a is in scope"); // pass
    });
    console.log(a); // undefined
    a = 1;
    console.log(a); // 1
    function inner() {}
    b = 2;
    if (a == 1) {
        c = 3;
    }
}

此外,请查看JavaScript的函数范围规则:http://www.w3schools.com/js/js_scope.asp