JavaScript,在';var';没有';var';
我理解以下函数,因为会发生变量提升。 foo() 然而,我不明白的是下面的部分。 我有参考错误,为什么JavaScript,在';var';没有';var';,javascript,hoisting,Javascript,Hoisting,我理解以下函数,因为会发生变量提升。 foo() 然而,我不明白的是下面的部分。 我有参考错误,为什么 foo() function foo() { console.log( a ); // Reference Error a = 2; } ---编辑--- 到目前为止,我从答案中了解到的是,第二个变量不起任何作用,我们不能使用任何未定义的变量 foo() function foo() { // we cannot use any undefined variable
foo()
function foo() {
console.log( a ); // Reference Error
a = 2;
}
---编辑---到目前为止,我从答案中了解到的是,第二个变量不起任何作用,我们不能使用任何未定义的变量
foo()
function foo() {
// we cannot use any undefined variable, which "a" here
console.log( a );
window.a = 2;
}
比如说
var a;
a; //undefined
b; //Reference error
在第一个声明中,
a
,但是undefined
,在第二个声明中它也未声明(在foo
或全局范围中找不到),因此抛出一个引用错误。由于没有var
声明,它不会被提升,并且在log语句之后在全局空间中定义,那么你还期待什么呢?@Bergiundefined
maybe@Bergi我不认为所谓的傻瓜回答了这个问题,这与全局/局部范围有关,这与提升有关。@Tushar:你认为这个傻瓜会更好吗?
var a;
a; //undefined
b; //Reference error