`with` 陳述式可將物件加入作用域鏈頂端,在區塊內直接存取該物件屬性無需重複前綴。雖語法糖看似方便,但**嚴格模式已禁用**、極難優化、易造成 Bug,現代開發**強烈不建議使用**。本文解析語法、風險與替代方案。
with (object) {
// 區塊內可直接存取 object 的屬性/方法
// 相當於隱性將 object 加入作用域鏈最前端
}
function Student(name, age) {
this.name = name;
this.age = age;
}
var stu = new Student('羅納爾多', 36);
// 使用 with 簡化
with (stu) {
console.log("Name: " + name + ", Age: " + age);
// 等同於:
// console.log("Name: " + stu.name + ", Age: " + stu.age);
}
// 伪代碼示意 with 內部查找順序
with (obj) {
identifier; // 查找順序:
// 1. obj 自身屬性
// 2. obj 原型鏈屬性
// 3. 外層作用域 (函式/模組/全域)
// 4. 全域物件
}
var x = 10;
var obj = { x: 20 };
with (obj) {
console.log(x); // 20 (obj.x)
x = 30; // 修改 obj.x 還是外層 x?取決於 obj 是否有 x
// 若 obj 無 x,則修改外層 x → 極易產生 Bug
}
console.log(obj.x); // 30
console.log(x); // 10 (若 obj 有 x) 或 30 (若 obj 無 x) - 行為不確定!
"use strict";
with (obj) { } // SyntaxError: Strict mode code may not include a with statement
const { name, age, address: { city } } = student;
console.log(name, age, city); // 直接使用,清晰可讀、可壓縮、可優化
// 手動建立短別名
const s = student;
console.log(s.name, s.age, s.address.city);
// 或
const { name, age } = student; // 只取需要的
(function(student) {
// 區塊內直接用 student.xxx
console.log(student.name);
})(student);
// 現代語法:安全存取巢狀屬性
const city = student?.address?.city?.name ?? 'Unknown';
console.log(city);
// 早期 jQuery 外掛常見模式
with (jQuery) {
// 內部大量使用 $, each, ajax 等
// 現代改用:const $ = jQuery; 或 import $ from 'jquery';
}
// 建構式內部批量設定屬性 (反模式)
function Config(options) {
with (this) {
for (var key in options) {
this[key] = options[key]; // 其實 this[key] 更清楚
}
}
}
// .eslintrc.js
module.exports = {
rules: {
'no-with': 'error', // 禁止使用 with
'no-restricted-syntax': ['error', 'WithStatement'] // 同義
}
};
`with` 是 JavaScript 設計失誤的遺產,嚴格模式禁用、現代工具鏈不支援、效能極差、語意模糊。