javascript - (javascript) 使用“call”调用 es6 getter
问题描述
我正在尝试创建一个(类)实例来复制另一个类的行为,但将其自身用作状态上下文(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)
我怎样才能使这样的工作?
解决方案
回想一下,类的属性获取器在其原型中结束
因此,要访问该方法,您可能希望从其原型中获取它:
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
推荐阅读
- python - Python什么时候释放内存?
- javascript - 将 React 添加到网站时,如何在多个文件中使用组件?
- swift - SwiftUI 列表行没有调整以适应内容
- multithreading - 多线程应用程序中的 GDB 条件断点
- c# - c# - 通过字符串列表“循环动画”
- sql - 使用第三个表连接两个表
- javascript - 使用 lodash groupBy 以正确的方式构建数组
- maven - 即使在 jar 存在之后,也没有找到顶点 jar 异常
- python - 为什么 discord.py 不允许我添加反应?
- javascript - 如何在不显示白屏的情况下导航页面 REACT