为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

富国沪深 2023-07-29 15:43:46
我尝试使用代理进行猴子补丁以在我的类中运行。如何访问和调用原始函数?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();
查看完整描述

2 回答

?
慕田峪7331174

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();


查看完整回答
反对 回复 2023-07-29
?
米琪卡哇伊

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 函数,那么您将陷入无限循环。


查看完整回答
反对 回复 2023-07-29
  • 2 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号