请问如何用Object.prototype扩展类的get/set方法?

class Label
{

    set string(value:string)
    {
    
    }
    
    get string():string
    {
    
    }
}

我知道可以用下面的代码扩展或重写一个成员,

Label.prototype.example = function(){}

那么,请问如何用Label.prototype扩展string的get/set方法?
或者其实应该用其他的我不知道的办法来扩展?

阅读 2.6k
3 个回答

Object.defineProperty

image.png

是想利用Object.defineProperty重写Label.prototype.string属性?

Object.defineProperty(Label.prototype, 'string', {
    configurable: true,
    enumerable: false,
    set(value) {
         console.log(`SubLabel.set & value=${value}`)
    },
    get() {
        return 'SubLabel.hello'
    }
})

//Test
var subLabel = new Label();
subLabel.string = 'test'; // SubLabel.set & value=test
console.log(subLabel.string); // SubLabel.hello

通过 Proxy,可以灵活地“定义”属性,而不需要使用 Object.defineProperties方法。

let lableProxy = new Proxy(Label.prototype, {
  get: (obj, prop) => {
    if (prop === 'string') {
      console.log('new string get')
    }
    // 可以添加对其他属性的附加操作
  },
  set: (obj, prop, value) => {
    if (prop === 'string') {
      console.log('new string set' + value)
    }
    // 可以添加对其他属性的附加操作
  }
});
let label = new Label();
label = Object.create(lableProxy)
label.string = 'A1'; // new string setA1
console.log(label.string); // new string get
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题