W3cubDocs

/JavaScript

Object.prototype.__defineSetter__()

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Warning: 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

__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 receives the following parameter:

val

An alias for the variable that holds the value attempted to be assigned to prop.

Return value

Description

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

Examples

Non-standard and deprecated way

const 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
const o = { set value(val) { this.anotherValue = val; } };
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5
// Using Object.defineProperty
const o = {};
Object.defineProperty(o, 'value', {
  set(val) {
    this.anotherValue = val;
  },
});
o.value = 5;
console.log(o.value); // undefined
console.log(o.anotherValue); // 5

Specifications

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet Deno Node.js
__defineSetter__
1
12
1
Starting with Firefox 48, 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.
11
9.5
3
4.4
18
4
10.1
1
1.0
1.0
0.10.0

See also

© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__