Search code examples
javascriptgetter-setter

How can i access getter and setter function of Object?


There is one object that has a property named password. This property is called by calling the set method. Then I defined the second setter method to the same property.But I want both the first setter method and the second setter method to work.For this, how can I access the first setter function?

//constant code
var obj = {
  get password() {
            return this._password;
        },
  set password(val) {
            this._password = new TextEncoder().encode(val);
        }
}
Object.defineProperty(obj,"password",{set:function(val){
//exectue first setter function of password
//execute second setter
this._password=val;}})

I can only modify the code. I can't make any changes to the code either.

How can I access first setter function?


Solution

  • You can keep original version of setter to call it inside of your new version:

    const originalSetPassword = Object.getOwnPropertyDescriptor(obj, "password").set;
    Object.defineProperty(obj, "password", {
      set: function(val) {
        originalSetPassword.call(obj, val);
        this._password=val;
      }
    });