我是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();
答案 0 :(得分:0)
由于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