在Secrets of the JavaScript Ninja这本书中,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();结论是,由于断言失败,"b还不在作用域中,直到它被声明“。但我认为情况并非如此,因为首先,b可能已经有了一个本地作用域,但它还不是一个“数字”。b实际上已经是一个局部作用域b,并且将隐藏任何全局b。
例如:
var b = 123;
function foo() {
b = 456;
var b = 789;
}
foo();
console.log(b); // prints out 123因为它输出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因此,我们可以再次看到,第一个打印输出不是123,而是undefined,这意味着b是一个本地作用域b,因此,b实际上已经在本书的示例中。
上面的描述和概念正确吗?
发布于 2013-02-21 16:11:50
事实上,这本书的结论是错误的。函数中任何地方的var b都意味着b存在于函数中的任何地方。这就是“提升”的含义。所有var和function声明都被提升到顶部,而不管它们出现在作用域中的什么位置。这个值还没有被赋值。
发布于 2013-02-21 16:39:04
关于代码:
assert(typeof b === "number", "b is in scope");
var b = 1;声明:
"b在声明之前还不在作用域中“
是错误的。b处于“作用域”内(因为它是在执行任何代码之前声明的,所以它是在执行任何代码之前创建的),但是还没有被赋值,因此typeof b返回undefined,测试失败。
上面的描述和概念正确吗?
是的,或多或少。一个更简单的证明是:
function foo() {
alert(b);
var b = 5;
}
function bar() {
alert(x);
x = 5;
}
foo() // 'undefined' since b is "in scope" but hasn't been assigned a value yet
bar() // throws an error since x isn't "in scope" until the following line.https://stackoverflow.com/questions/14997277
复制相似问题