with 陳述式可將指定物件加入作用域鏈最前端,使區塊內的識別符優先解析為該物件的屬性。雖然能減少重複輸入物件名稱,但因效能、除錯困難及嚴格模式禁用等原因,現代開發強烈不建議使用。
with (object) {
statement
}
// 未使用 with
const x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10);
const y = Math.tan(14 * Math.E);
// 使用 with
with (Math) {
const x = cos(3 * PI) + sin(LN10);
const y = tan(14 * E);
}
<script>
with (document) {
write('fileSize=' + fileSize);
title = 'My title';
bgColor = 'teal';
}
</script>
title 時無法一眼判斷是區域變數還是 document.title。SyntaxError。with 區塊內賦值給不存在的識別符會建立全域變數,而非物件屬性。// 解構賦值
const { cos, sin, tan, PI, LN10, E } = Math;
const x = cos(3 * PI) + sin(LN10);
const y = tan(14 * E);
// 或使用簡短變數別名
const M = Math;
const x = M.cos(3 * M.PI) + M.sin(M.LN10);
with 屬於歷史遺留語法,僅存在於舊代碼中。新專案嚴禁使用,改用解構、模組導入或變數別名達成同樣簡潔效果。