Open In App

JavaScript Object.prototype.__defineSetter__() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The  __defineSetter__() method is used to bind an object’s property to a function which will be called when an attempt is made to set the specified property. It is recommended to use the object initializer syntax or the Object.defineProperty() API instead of this method as it is being deprecated.

Syntax: 

obj.__defineSetter__( prop, fun )

Parameters: This function accepts two parameters as given above and described below:

  • prop: It is a string that contains the name of the property to bind to the given function.
  • fun: It is a function to be called when there is an attempt to set the specified property. The val parameter of the function can be used to specify an alias for the variable that holds the value attempted to be assigned to the prop.

Return Values: This method returns undefined.

Example 1: Using the __defineSetter__() method

Javascript




<script>
    let tmpObj = {};
    tmpObj.__defineSetter__('setValue', function(val) { 
    this.currentValue = val;
    });
      
    tmpObj.setValue = 10;
    console.log(tmpObj.setValue);
    console.log(tmpObj.currentValue);
</script>


 Output:

undefined
10

Example 2: Using the standard-compliant way using object initializer syntax and Object.defineProperty() API

Javascript




<script>
    // Using the set operator
    var obj1 = { 
        set setValue(val) { this.currentValue = val; } 
    };
      
    obj1.setValue = 10;
    console.log(obj1.setValue);
    console.log(obj1.currentValue);
      
    // Using Object.defineProperty
    var obj2 = {};
    Object.defineProperty(obj2, 'value', {
      set: function(val) {
        this.currentValue = val;
      }
    });
    obj2.value = 2;
    console.log(obj2.value);
    console.log(obj2.currentValue); 
</script>


Output: 

undefined
10
undefined
2

We have a complete list of Javascript Object Methods, to check those please go through the Javascript Object Complete Reference article.

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari


Last Updated : 10 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads