我正在尝试创建一个(类)实例,它复制另一个类的行为,但使用它自己作为状态上下文(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)我怎么才能让这样的东西工作呢?
发布于 2020-04-13 20:05:10
回想一下,类的属性getter在其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
https://stackoverflow.com/questions/61186982
复制相似问题