最近我在看《你不知道的JavaScript》中卷,在這里我也強(qiáng)烈建議你也讀一讀這本書,其中提到了一個函數(shù)參數(shù)和arguments的區(qū)別,在此做一個記錄。
本文將用代碼來說明兩者的區(qū)別。
如果你不知道arguments是什么,我建議你看看mdn的介紹。
ES5引入了嚴(yán)格模式,在嚴(yán)格模式中改變了arguments和函數(shù)參數(shù)之間的關(guān)系,本文將分為兩種情況分別說明。
直接上代碼,先來看調(diào)用時缺省參數(shù)的情況
function a1(x) {
x = 2;
console.log(x, arguments[0]);
}
a1(); // 2 undefined
function a2(x) {
arguments[0] = 2;
console.log(x, arguments[0]);
}
a2(); // undefined 2
再來看調(diào)用時傳入?yún)?shù)的情況
function a3(x) {
x = 2;
console.log(x, arguments[0]);
}
a3(1); // 2 2
function a4(x) {
arguments[0] = 2;
console.log(x, arguments[0]);
}
a4(1); // 2 2
可以看到如果缺省參數(shù),arguments和參數(shù)是隔離開的;如果傳入?yún)?shù),arguments和參數(shù)是雙向綁定的。
再來看看嚴(yán)格模式,直接上代碼
function b1(x) {
'use strict';
x = 2;
console.log(x, arguments[0]);
}
b1(); // 2 undefined
function b2(x) {
'use strict';
arguments[0] = 2;
console.log(x, arguments[0]);
}
b2(); // undefined 2
function b3(x) {
'use strict';
x = 2;
console.log(x, arguments[0]);
}
b3(1); // 2 1
function b4(x) {
'use strict';
arguments[0] = 2;
console.log(x, arguments[0]);
}
b4(1); // 1 2
在嚴(yán)格模式下,無論參數(shù)是否缺省,arguments和參數(shù)都是隔離開的。
在嚴(yán)格和非嚴(yán)格模式下行為會有不同,大家小心別踩坑,祝好。
更多建議: