Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
set 語法會在物件屬性被嘗試定義時,將其屬性綁定到要呼叫的函式內。
要綁定到給定函式的屬性名。
val變數別名,該變數擁有要被嘗試安插到 prop 的數值。
expression從 ECMAScript 2015 開始,可以使用計算屬性名(computed property name)表達式,綁定到給定函式。
JavaScript 的 setter 能在嘗試修改指定屬性時,執行給定函式。Setter 最常用於和 getter 一同建立虛擬屬性(pseudo-property)。你不可能給同一個屬性賦予 setter 與實際值。
使用 set 語法時,請注意以下情況:
delete 操作符可移除 setter。
這裡會給物件 language 定義稱為 current 的虛擬屬性。在指派數值時 log 會和該值一同更新:
請注意 current is not defined and any attempts to access it will result in undefined.
若想移除 setter 的話,可以直接使用 delete:
To append a setter to an existing object later at any time, use Object.defineProperty().
| ECMAScript® 2027 Language Specification # sec-method-definitions |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2025年7月16日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.