如何解决是否可以将代理对象绑定到 ES6 类构造函数?
在 ES5^ 中,我可以创建一个 proxy
对象并将其绑定到其他函数构造函数,请在下面的示例中查看我想要做什么:
function X() {
this.x = `${this.anyAttr} it's a trap`;
}
function Y() {
this.y = `${this.anyAttr} do the barrel roll`;
}
function Z(...a) {
const proxy = new Proxy(this,{
get(target,key) {
if (target[key]) {
return Reflect.get(target,key);
}
return "FROM Z:";
}
});
X.apply(proxy,a);
Y.apply(proxy,a);
return proxy;
}
const obj = new Z();
console.log(obj.someAttr) // FROM Z:
console.log(obj.x) // FROM Z: it's a trap
console.log(obj.y) // FROM Z: do the barrel roll
我想做同样的事情,但是使用 ES6 Class 语法,但是 apply
方法不能与 ES6 类一起使用,请参见下面的示例:
class X {
constructor() {
this.x = `${this.anyAttr} it's a trap`
}
}
class Y {
constructor() {
this.y = `${this.anyAttr} do the barrel roll`
}
}
function Z(...a) {
const proxy = new Proxy(this,{
get(target,key) {
if (target[key])
return Reflect.get(target,key)
return "FROM Z:"
}
})
X.apply(proxy,a) // Uncaught TypeError: Class constructor X cannot be invoked without 'new' at new Z
Y.apply(proxy,a) // Uncaught TypeError: Class constructor Y cannot be invoked without 'new' at new Z
return proxy;
}
const obj = new Z()
具体来说,我需要混合类,但在构造超类之前,我需要链接一个 proxy
对象来执行一些黑魔法,所以...
有没有办法做一些类似于第一个例子但使用 ES6 类的事情?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。