(javascript) 使用 "call" 调用 es6 getter

(javascript) invoke es6 getter using "call"

我正在尝试创建一个 (class) 实例来复制另一个 class 的行为,但将其自身用作状态上下文 (this)。普通函数工作正常(如下例中的 setValue 函数),但 getter 不起作用。这是一个简单的例子:

const should = require('chai').should();

class One {
    setValue(val) {
        this._val = val;
    }

    get val() {
        return this._val;
    }
}

class Two {
    constructor(one) {
        this.one = one;
    }

    setValue(val) {
        this.one.setValue.call(this, val);
    }

    get val() {
        this.one.val.call(this);
    }
}

let one = new One();
let two = new Two(one);
one.setValue(1);
two.setValue(2);
one.val.should.equal(1);
two.val.should.equal(2);

以上代码在最后一行出现错误:

TypeError: this.one.val.call is not a function
    at Two.get val [as val] (C:\all\code\node-tests\invoke_getter.js:23:22)
    at Object.<anonymous> (C:\all\code\node-tests\invoke_getter.js:32:5)

我怎样才能做出这样的作品?

回想一下 属性 getters for class 以其 prototype

结束

所以要访问该方法,您可能需要从它的原型中获取它:

const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.one), 'val')

然后您可以在 two 实例上调用 getter:

class One {
  setValue(val) {
    this._val = val
  }

  get val() {
    return this._val
  }
}

class Two {
  constructor(one) {
    this.one = one
  }

  setValue(val) {
    this.one.setValue.call(this, val)
  }

  get val () {
    const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.one), 'val')
    return desc.get.call(this)
  }
}

const one = new One()
const two = new Two(one)
one.setValue(1)
console.log(two.val) // undefined (since _val does not exist on two yet)
two.setValue(2)
console.log(two.val) // 2
two._val = 3
console.log(two.val) // 3