在看JS高級程序設計時忽然想到這個問題,眾所周知,直接賦值一個變量而為聲明,會產生一個全局變量(或者說是全局對象的屬性),但用var聲明的變量 和 直接賦值而并未聲明的變量 都有哪些區別呢,這是我在百度知道上搜到的,個人感覺總結的很全:
1.在函數作用域內 加var定義的變量是局部變量,不加var定義的就成了全局變量。
使用var定義
var a = 'hello World';
function bb(){
var a = 'hello Bill';
console.log(a);?
}
bb() // 'hello Bill'
console.log(a); // 'hello world'
不使用var定義
var e = 'hello world';
function cc(){
e = 'hello Bill';
console.log(e); // 'hello Bill'
}
cc() // 'hello Bill'
console.log(e) // 'hello Bill'
2.在全局作用域下,使用var定義的變量不可以delete,沒有var 定義的變量可以delete.也就說明隱含全局變量嚴格來說不是真正的變量,而是全局對象的屬性,因為屬性可以通過delete刪除,而變量不可以。
3.使用var 定義變量還會提升變量聲明,即(不理解的說明要多理解理解預編譯了)
使用var定義:
function hh(){
console.log(a);
var a = 'hello world';
}
hh() //undefined
不使用var定義:
function hh(){
console.log(a);
a = 'hello world';
}
hh() // 'a is not defined'
這就是使用var定義的變量的聲明提前。
4.在ES5的'use strict'模式下,如果變量沒有使用var定義,就會報錯。?