js set get hook

普通方法的hook非常so easy, 就不用记录了。

现在记录一下hook set get方法:

class A{
  constructor(){
    this._age = 0;
  }

  get age(){
    return this._age;
  }

  set age(v){
    console.log('aa')
    this._age = v;
  }
}

let a = new A();

const {get:oldGet, set:oldSet} = Object.getOwnPropertyDescriptor(a.constructor.prototype, "age");
Object.defineProperty(a, 'age', {
  set(v){
    console.log('你设置的值是:', v);
    oldSet.call(this, v);
  },
  get(){
    let ret = oldGet.call(this);
    console.log('你获取的值:', ret);
    return ret
  }
});

console.log(a.age)
a.age = 10;
console.log(a.age)
console.log(a._age)

  

 

posted @ 2023-01-06 17:57  Please Call me 小强  阅读(89)  评论(0编辑  收藏  举报