Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

我們的志工尚未將此文章翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!

This feature is deprecated in favor of defining setters using the object initializer syntax or the Object.defineProperty() API.

However, as it is widely implemented and used on the Web, it is very unlikely that browsers will stop implementing it.

The __defineSetter__ method binds an object's property to a function to be called when an attempt is made to set that property.

Syntax

obj.__defineSetter__(prop, fun)

Parameters

prop
A string containing the name of the property to be bound to the given function.
fun
A function to be called when there is an attempt to set the specified property. This function takes the form
function(val) { . . . }
val
An alias for the variable that holds the value attempted to be assigned to prop.

Return value

undefined.

Description

The __defineSetter__ method allows a setter to be defined on a pre-existing object.

Examples

// Non-standard and deprecated way

var o = {};
o.__defineSetter__('value', function(val) { this.anotherValue = val; });
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5


// Standard-compliant ways

// Using the set operator
var o = { set value(val) { this.anotherValue = val; } };
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5

// Using Object.defineProperty
var o = {};
Object.defineProperty(o, 'value', {
  set: function(val) {
    this.anotherValue = val;
  }
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5

Specifications

Specification Status Comment
ECMAScript 2017 Draft (ECMA-262)
The definition of 'Object.prototype.__defineSetter__()' in that specification.
Draft Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) 11 (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) ? (Yes) (Yes)

Compatibility notes

  • Starting with Firefox 48 (Firefox 48 / Thunderbird 48 / SeaMonkey 2.45), this method can no longer be called at the global scope without any object. A TypeError will be thrown otherwise. Previously, the global object was used in these cases automatically, but this is no longer the case (bug 1253016).

See also

文件標籤與貢獻者

 最近更新: eduardoboucas,