1. LHS和RHS
RHS(right-hand side)查詢與簡單地查找某個(gè)變量的值別無二致昵骤,
而LHS(left-hand side)查詢則是試圖找到變量的容器本身,從而可以對(duì)其賦值阐滩。
(1)RHS找不到變量
如果RHS查詢?cè)谒星短椎淖饔糜蛑斜閷げ坏剿璧淖兞炕Σ福婢蜁?huì)拋出異常叨橱。
值得注意的是元媚,ReferenceError是非常重要的異常類型。
function f() {
a;
}
f();
console.assert(window.a === 1);
// Uncaught ReferenceError: a is not defined
(2)LHS找不到變量
當(dāng)引擎執(zhí)行LHS查詢時(shí)弯予,如果在頂層(全局作用域)中也無法找到目標(biāo)變量戚宦,
全局作用域中就會(huì)創(chuàng)建一個(gè)具有該名稱的變量,并將其返還給引擎锈嫩,前提是程序運(yùn)行在非 “嚴(yán)格模式”下受楼。
function f() {
a = 1;
}
f();
console.assert(window.a === 1);
在嚴(yán)格模式中LHS查詢失敗時(shí),并不會(huì)創(chuàng)建并返回一個(gè)全局變量呼寸,
引擎會(huì)拋出同RHS查詢失敗時(shí)類似的 ReferenceError 異常艳汽。
function f() {
'use strict';
a = 1;
}
f();
console.assert(window.a === 1);
// Uncaught ReferenceError: a is not defined
2. 嚴(yán)格模式下不能使用with
function f() {
'use strict';
with ({ a: 1 }) { };
}
f();
// Uncaught SyntaxError: Strict mode code may not include a with statement
3. with找不到對(duì)象屬性,會(huì)創(chuàng)建全局變量
function f() {
const obj = { a: 1 };
with (obj) {
a = 2;
};
console.assert(obj.a === 2);
console.assert(window.a === undefined);
with (obj) {
b = 2; // 如果obj中找不到b屬性等舔,則會(huì)創(chuàng)建全局變量
};
console.assert(obj.b === undefined);
console.assert(window.b === 2);
}
f();
4. 使用塊作用域幫助垃圾收集
function f() {
// 可以做其他一些事情
{
let bigData = {};
// 使用bigData
}
// bigData已經(jīng)不可用了
// bigData is not defined
}
f();
在塊作用域中使用let
聲明的變量骚灸,在塊外部如果沒有其他引用將無法訪問,
這有助于垃圾收集器更快的回收塊內(nèi)數(shù)據(jù)慌植。
在塊的外部甚牲,通過引用方式仍然可以訪問塊內(nèi)數(shù)據(jù),
function f() {
const a = {};
{
let bigData = {};
a.b = bigData;
}
a.b; // 通過引用訪問塊內(nèi)數(shù)據(jù)
}
f();
5. let在每次迭代中重新綁定
for循環(huán)中使用let
會(huì)為每一次循環(huán)重新創(chuàng)建一個(gè)新的塊作用域蝶柿。
for (let i = 0; i < 5; i++) {
//
}
// 相當(dāng)于
{
let j;
for (j = 0; j < 5; j++) {
let i = j;
//
}
}
例子丈钙,
const q = [];
for (let i = 0; i < 5; i++) {
q.push(() => console.log(i));
}
q.forEach(f => f()); // 0 1 2 3 4
而var
則不會(huì)創(chuàng)建新的塊作用域,
const q = [];
for (var i = 0; i < 5; i++) {
q.push(() => console.log(i));
}
q.forEach(f => f()); // 5 5 5 5 5
6. 在ES6之前實(shí)現(xiàn)塊作用域
{
let a = 1;
console.log(a); // 1
}
a; // Uncaught ReferenceError: a is not defined
使用catch
實(shí)現(xiàn)塊作用域交汤,
try{
throw 1;
}catch(a){
console.log(a); // 1
}
a; // Uncaught ReferenceError: a is not defined