gpt4 book ai didi

javascript - 混合构造函数并在 Javascript 代理对象上应用陷阱

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:10 26 4
gpt4 key购买 nike

我有一个类,我想对其应用代理,观察方法调用和构造函数调用:

计算器.js

class Calc {
constructor(){}

add(a, b) {
return a+b;
}

minus(a, b) {
return a-b;
}
}

module.exports = Calc;

index.js

const Calculator = require('./src/Calculator');

const CalculatorLogger = {
construct: function(target, args, newTarget) {
console.log('Object instantiated');
return new target(...args);
},
apply: function(target, thisArg, argumentsList) {
console.log('Method called');
}
}
const LoggedCalculator = new Proxy(Calculator, CalculatorLogger);
const calculator = new LoggedCalculator();
console.log(calculator.add(1,2));

调用时,我希望输出为:

Object instantiated

Method called

然而,apply 没有被调用,我假设这是因为我将 Proxy 附加到 Calculator 类,而不是实例化的对象,所以不知道 apply陷阱。

我如何构建一个包罗万象的代理来“观察”方法调用和构造函数调用。

最佳答案

I assume that this is because I am attaching the Proxy to the Calculator class, but not the instantiated object, and so doesn't know about the apply trap.

你完全正确,代理作用于对象,所以除非调用 Calculator 类的函数属性,否则它不会调用 apply,如下所示:

class Calculator {
constructor() {
this.x = 1;
}

instanceFunction() {
console.log('Instance function called');
}

static staticFun() {
console.log('Static Function called');
}

}

const calcHandler = {
construct(target, args) {
console.log('Calculator constructor called');
return new target(...args);
},
apply: function(target, thisArg, argumentsList) {
console.log('Function called');
return target(...argumentsList);
}
};

Calculator = new Proxy(Calculator, calcHandler);

Calculator.staticFun();

const obj = new Calculator();

obj.instanceFunction();

清楚了,用代理包装 Calculator 实例的方法可能是:

  1. 让类代理代理 construct 上的实例:

const CalculatorInstanceHandler = {
apply(target, thisArg, args) {
console.log('Function called');
return target(...args);
}
}

const CalculatorClassHandler = {
construct(target, args) {
const instance = new target(...args);
return new Proxy(instance, CalculatorInstanceHandler);
}
}

  1. Calculator 类中有一个工厂函数以创建proxified 实例:

const CalculatorInstanceHandler = {
apply(target, thisArg, args) {
return target(...args);
}
};

class Calculator {

static getNewCalculator() {
const instance = new Calculator();

return new Proxy(instance, CalculatorInstanceHandler);

}
}

关于javascript - 混合构造函数并在 Javascript 代理对象上应用陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50842477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com