2 回答

TA贡献1828条经验 获得超13个赞
处理程序apply
是用原始函数作为参数来调用的:
class foo {
x = 10;
bar() {
console.log({ x: this.x });
}
}
foo.prototype.bar = new Proxy(foo.prototype.bar, {
apply: function(target, thisArg, argumentsList) {
console.log("xxx");
Reflect.apply(target, thisArg, argumentsList);
},
});
new foo().bar();
(一般来说,这些Reflect
函数可用于委托给正在包装的同名代理陷阱。)
另请注意,与通常的代理一样,您可能不需要它们。
class foo {
x = 10;
bar() {
console.log({ x: this.x });
}
}
const originalBar = foo.prototype.bar;
Object.assign(foo.prototype, {
bar() {
console.log("xxx");
originalBar.call(this);
},
});
new foo().bar();

TA贡献1998条经验 获得超6个赞
请注意,this您的 apply 函数中的 目标是其自己的范围。这意味着它引用 (apply) 函数本身。
您可以向 apply 函数提供参数
apply: function(target, that, args) { ... }
是targetbar 函数,是that引用父对象并且args......你可以猜到:-)
class foo {
x = 10;
bar(value) {
console.log('Class variable x: ', x);
console.log('Method Parameter: ', value)
}
}
foo.prototype["_bar"] = foo.prototype.bar;
foo.prototype.bar = new Proxy(foo.prototype.bar, {
apply: function(target, that, args) {
console.log("Target", target);
console.log("THAT", that);
console.log("args", args);
}
});
new foo().bar('World');
如果您调用target.bar(args)apply 函数,那么您将陷入无限循环。
添加回答
举报