nop*_*ole 2 javascript scope hoisting
在" 忍者的秘密 "一书中,p.43 - 46,它有一些代码如:
function assert(flag, msg) {
if (!flag) {
console.log("Assertion failed for: " + msg);
}
}
function outer() {
var a = 1;
function inner() { }
assert(typeof b === "number", "b is in scope");
var b = 1;
}
outer();
Run Code Online (Sandbox Code Playgroud)
结论是,由于断言失败,"b尚未在范围内,直到声明为止".但我认为不是这样,因为首先,b已经有一个本地范围,但只是它还不是一个"数字". b实际上已经是一个局部范围b,并将影响任何全球范围b.
例如:
var b = 123;
function foo() {
b = 456;
var b = 789;
}
foo();
console.log(b); // prints out 123
Run Code Online (Sandbox Code Playgroud)
因为它打印出来123,所以我们可以看到,当b = 456;执行该行时,b已经是本地范围b.(即使在作业之前它尚未初始化).
此外,我们可以打印出来而不是分配给b:
var b = 123;
function foo() {
console.log(b); // prints out undefined
var b = 789;
}
foo();
console.log(b); // prints out 123
Run Code Online (Sandbox Code Playgroud)
再次,我们可以看到第一个打印输出不是,123但是undefined,意味着它b是一个局部范围b,因此,b实际上已经在本书的范例中.
以上描述和概念是否正确?
的确,这本书的结论是错误的.var b 任何地方里面的函数是指b存在的任何地方里面的功能.这就是"吊装"的意思.所有var和function声明都被提升到顶部,无论它们在范围内出现在何处.该值尚未分配.
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |