Object.assign getters and setters in constructor

后端 未结 1 1698
情深已故
情深已故 2020-12-01 21:27

I try to define getter and setter in constructor via Object.assign:

function Class() {
  Object.assign(this, {
    get prop() { console.log(\'c         


        
相关标签:
1条回答
  • 2020-12-01 22:05

    The answer to all three of your questions is the same: Object.assign reads the value of the property from the source object, it doesn't copy getters/setters.

    You can see that if you look at the property descriptor:

    var source = {
      get prop() { },
      set prop(v) { }
    };
    console.log("descriptor on source", Object.getOwnPropertyDescriptor(source, "prop"));
    var target = Object.assign({}, source);
    console.log("descriptor on target", Object.getOwnPropertyDescriptor(target, "prop"));

    To define that property on this inside Class, use defineProperty:

    function Class() {
      Object.defineProperty(this, "prop", {
        get() { console.log('call get') },
        set(v) { console.log('call set') },
      });
    }
    var c = new Class();
    console.log(c.prop); // => 'call get', undefined
    c.prop = 'change'; // => 'call set'
    console.log(c.prop); // => 'call get', undefined

    0 讨论(0)
提交回复
热议问题