Object.prototype.__defineSetter__() - JavaScript 编辑

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
ECMAScript (ECMA-262)
The definition of 'Object.prototype.__defineSetter__()' in that specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:45 次

字数:5103

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文