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. When I log out "a" it behaves as expected. 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.