2 回答

TA貢獻1828條經(jīng)驗 獲得超13個贊
處理程序apply
是用原始函數(shù)作為參數(shù)來調(diào)用的:
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
函數(shù)可用于委托給正在包裝的同名代理陷阱。)
另請注意,與通常的代理一樣,您可能不需要它們。
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條經(jīng)驗 獲得超6個贊
請注意,this您的 apply 函數(shù)中的 目標(biāo)是其自己的范圍。這意味著它引用 (apply) 函數(shù)本身。
您可以向 apply 函數(shù)提供參數(shù)
apply: function(target, that, args) { ... }
是targetbar 函數(shù),是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');
如果您調(diào)用target.bar(args)apply 函數(shù),那么您將陷入無限循環(huán)。
添加回答
舉報