我如何访问对象的getter和setter函数?

问题描述 投票:0回答:1

[有一个对象具有名为password的属性。通过调用set方法来调用此属性。然后我将第二个setter方法定义为相同的属性。但是我希望第一个setter方法和第二个setter方法都可以工作。为此,如何访问第一个setter函数?

//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;}})

我只能修改代码。我也无法对代码进行任何更改。

我如何使用第一个设置器功能?

javascript getter-setter
1个回答
1
投票

您可以保留二传手的原始版本以在新版本中调用它:

const originalSetPassword = Object.getOwnPropertyDescriptor(obj, "password").set;
Object.defineProperty(obj, "password", {
  set: function(val) {
    originalSetPassword.call(obj, val);
    this._password=val;
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.