欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談JavaScript中定義變量時(shí)有無(wú)var聲明的區(qū)別

 更新時(shí)間:2014年08月18日 15:41:36   投稿:hebedich  
這篇文章主要介紹了JavaScript中定義變量時(shí)有無(wú)var聲明的區(qū)別分析以及示例分享,需要的朋友可以參考下

前段時(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,沒(méi)有var 定義的變量可以delete.也就說(shuō)明隱含全局變量嚴(yán)格來(lái)說(shuō)不是真正的變量,而是全局對(duì)象的屬性,因?yàn)閷傩钥梢酝ㄟ^(guò)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'模式下,如果變量沒(méi)有使用var定義,就會(huì)報(bào)錯(cuò)。

相關(guān)文章

最新評(píng)論