"use strict";`(字符串表達式,舊引擎忽略)。// 無 with
objectWithLongName1.property1 = value1;
objectWithLongName1.property2 = value2;
objectWithLongName1.method1();
// 有 with
with (objectWithLongName1) {
property1 = value1;
property2 = value2;
method1();
}
塊內標識符解析規則:先在 with 對象上查找屬性,找不到再往外層作用域查找。導致:
// with (obj) { prop = val; } 等價於:
if (obj.prop !== undefined) {
if (obj.val !== undefined) obj.prop = obj.val; // 情況1
else obj.prop = val; // 情況2
} else {
if (obj.val !== undefined) prop = obj.val; // 情況3
else prop = val; // 情況4
}
// 四種可能,程序員難以控制,極易產生 Bug
with (objectWithLongName1) {
.property1 = value1; // 明確表示訪問 with 對象屬性
.method1();
}
在點號前加 `.` 明確區分屬性訪問與外層變量,但 ES 標準未採納。
const { property1, property2, method1 } = objectWithLongName1;
property1 = value1;
property2 = value2;
method1();
const o = objectWithLongName1;
o.property1 = value1;
o.property2 = value2;
o.method1();
(function(o1, o2, props) {
props.forEach(p => o1[p] = o2[p]);
})(objectWithLongName1, objectWithLongName2, ['prop1','prop2',...,'prop10']);