代理可以检测到子类正在向类添加方法吗?

问题描述 投票:0回答:2

给出这样的课程:

class A {}

是否可以以任何方式进行修改,以便我可以在方法像这样子类化时进行代理:

// proxy the `A` object in some way
const handler = {
  get(target, property) {
    console.log("getting", arguments);
    return target[property];
  },
  set(target, property, value) {
    console.log("setting", arguments);
    return target[property] = value;
  },
};

const A_proxied = new Proxy(A, handler);

我希望在以下情况下记录消息

setting hello
(或类似消息)。

class B extends A_proxied {
  hello() {
    return "world";
  }
}

上面的代码只记录

getting prototype
,没有其他内容。有什么想法吗?

javascript class es6-proxy
2个回答
-1
投票

不要使用应为此子类化的

class
。继承对于您的问题来说是错误的解决方案,代理也无济于事。

如果您希望某人在定义类时执行代码,请给他们一个要调用的函数:

const B = A(class {
  hello() {
    return "world";
  }
});

您可以将其声明为

function A(cls) {
  for (const key of Object.getOwnPropertyNames(cls.prototype)) {
    if (key == 'constructor') continue;
    console.log(`setting ${key}`);
  }
  return cls;
}

-1
投票

construct
的处理程序中使用
Proxy
陷阱:

// proxy the `A` object in some way
const handler = {
  construct(_, args, constructor){
    Object.getOwnPropertyNames(constructor.prototype).forEach(name => name === 'constructor' || console.log('setting', name));
    return Reflect.construct(...arguments);
  }
};

class A{}

const A_proxied = new Proxy(A, handler);

class B extends A_proxied {
  hello() {
    return "world";
  }
}

const b = new B;

© www.soinside.com 2019 - 2024. All rights reserved.