是否可以将代理对象绑定到 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 (将#修改为@)