Open In App

JavaScript Object.prototype.__defineSetter__() Method

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:

Return Values: This method returns undefined.



Example 1: Using the __defineSetter__() method




<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




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


Article Tags :