如何使用代理访问类中的原始函数?

我尝试使用代理进行猴子补丁以在我的类中运行。


如何访问和调用原始函数?


class foo {

  x = 10;


  bar() {

    console.log({ x: this.x });

  }

}


foo.prototype.bar = new Proxy(foo.prototype.bar, {

  apply: function() {

    console.log("xxx");

    console.log({ that: this });


    this.bar();

  }

});


new foo().bar();

富国沪深
浏览 164回答 2
2回答

慕田峪7331174

处理程序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();

米琪卡哇伊

请注意,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 函数,那么您将陷入无限循环。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript