简体   繁体   English

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

[英]Variable scope and testing with qUnit

I'm new to qUnit testing and having trouble to understand why my variable "a" passes a scope test, even if the test is called before "a" was defined. 我是qUnit测试的新手,即使知道在定义“ a”之前调用了该测试,也很难理解为什么我的变量“ a”通过了范围测试。 When I log out "a" it behaves as expected. 当我注销“ a”时,其行为符合预期。 Can anyone give me a hint? 谁能给我一个提示?

Here's the code: 这是代码:

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();

Because of JavaScript's hoisting "a" is really declared at the top of your function but is initialized at the point in your code where you assign it a value. 由于JavaScript的吊起, “ a”实际上是在函数顶部声明的,但是在代码中为其分配值的点进行了初始化。

So, when your code is interpreted, it actually looks more like this: 因此,当您的代码被解释时,它实际上看起来像这样:

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;
    }
}

Also, take a look at JavaScript's function scoping rules: http://www.w3schools.com/js/js_scope.asp 此外,请查看JavaScript的功能范围规则: http : //www.w3schools.com/js/js_scope.asp

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

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