繁体   English   中英

可变范围和使用qUnit进行测试

[英]Variable scope and testing with qUnit

我是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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