set 語法會在物件屬性被嘗試定義時,將其屬性綁定到要呼叫的函式內。

語法

{set prop(val) { . . . }}
{set [expression](val) { . . . }}

參數

prop
要綁定到給定函式的屬性名。
val
變數別名,該變數擁有要被嘗試安插到 prop 的數值。
expression
從 ECMAScript 2015 開始,可以使用計算屬性名(computed property name)表達式,綁定到給定函式。

描述

JavaScript 的 setter 能在嘗試修改指定屬性時,執行給定函式。Setter 最常用於和 getter 一同建立虛擬屬性(pseudo-property)。你不可能給同一個屬性賦予 setter 與實際值。

使用 set 語法時,請注意以下情況:

delete 操作符可移除 setter。

示例

在物件初始器的新物件定義 setter

這裡會給物件 language 定義稱為 current 的虛擬屬性。在指派數值時 log 會和該值一同更新:

var language = {
  set current(name) {
    this.log.push(name);
  },
  log: []
}

language.current = 'EN';
console.log(language.log); // ['EN']

language.current = 'FA';
console.log(language.log); // ['EN', 'FA']

請注意 current is not defined and any attempts to access it will result in undefined.

使用 delete 操作符移除 setter

若想移除 setter 的話,可以直接使用 delete

delete o.current;

針對已存在屬性的 setter 使用 defineProperty

To append a setter to an existing object later at any time, use Object.defineProperty().

var o = {a: 0};

Object.defineProperty(o, 'b', { set: function(x) { this.a = x / 2; } });

o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.a) // 5

使用計算屬性名

var expr = 'foo';

var obj = {
  baz: 'bar',
  set [expr](v) { this.baz = v; }
};

console.log(obj.baz); // "bar"
obj.foo = 'baz';      // 跑 setter
console.log(obj.baz); // "baz"

規範

規範 狀態 註解
ECMAScript 5.1 (ECMA-262)
The definition of 'Object Initializer' in that specification.
Standard 初始定義。
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Method definitions' in that specification.
Standard 增加計算屬性名。
ECMAScript Latest Draft (ECMA-262)
The definition of 'Method definitions' in that specification.
Draft  

瀏覽器相容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
setChrome Full support 1Edge Full support YesFirefox Full support 2IE Full support 9Opera Full support 9.5Safari Full support 3WebView Android Full support 1Chrome Android Full support 18Edge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
Computed property namesChrome Full support 46Edge Full support YesFirefox Full support 34IE No support NoOpera Full support 47Safari No support NoWebView Android Full support 46Chrome Android Full support 46Edge Mobile Full support YesFirefox Android Full support 34Opera Android Full support YesSafari iOS No support NoSamsung Internet Android Full support 5.0nodejs Full support Yes

Legend

Full support  
Full support
No support  
No support

參見

文件標籤與貢獻者

此頁面的貢獻者: iigmir
最近更新: iigmir,