【问题标题】:Variable scope and testing with qUnit使用 qUnit 进行变量范围和测试
【发布时间】:2015-11-24 12:58:15
【问题描述】:

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


    【解决方案1】:

    因为 JavaScript 的 hoisting "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

    【讨论】:

    • 感谢您的快速回答。在您链接的文章中,它说声明被提升但初始化不是(就像在您重写的代码中一样)。但是“typeof a”不应该是“未定义”吗?
    • 我同意在代码执行的那一点上它不会是“未定义的”是令人困惑的。我的印象是 qunit 的“测试”函数是同步的,所以它不应该被赋予“数字”类型。
    猜你喜欢
    • 2017-09-25
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多