我是 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的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
关于javascript - 变量范围和使用 qUnit 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33894361/