Search code examples
javascriptoopobjectgetter-settergetter

How to reassign an objects "getter" method?


Lets say theres an object with a getter method.

var person = {
 name : "John",
 get title(){
 return "Dr." + this.name
 }
}
>>>person.title
>>>"Dr.John"

I would like to reassign the getter method.

person.title = function (){return "Mr." + this.name}

Is there any way? Or at least create one dynamically or similar workarounds?


Solution

  • You can use Object.defineProperty

    var person = {
    	name: "John",
    	get title() {
    		return "Dr." + this.name
    	}
    }
    
    console.log(person.title)
    
    Object.defineProperty(person, "title", {
    	get: function() {
    		return "Mr." + this.name
    	}
    });
    
    console.log(person.title)