前段時(shí)間回答了一個(gè)關(guān)于定義變量時(shí)使用關(guān)鍵字var與否的區(qū)別,總結(jié)回顧一下。
1.在函數(shù)作用域內(nèi) 加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 a = 'hello World';function bb(){ a = 'hello Bill'; console.log(a); }bb() //'hello Bill'console.log(a); //'hello Bill'
2.在全局作用域下,使用var定義的變量不可以delete,沒有var 定義的變量可以delete.也就說明隱含全局變量嚴(yán)格來說不是真正的變量,而是全局對(duì)象的屬性,因?yàn)閷傩钥梢酝ㄟ^delete刪除,而變量不可以。
3.使用var 定義變量還會(huì)提升變量聲明,即
使用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定義,就會(huì)報(bào)錯(cuò)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注