亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用代理訪問類中的原始函數?

如何使用代理訪問類中的原始函數?

富國滬深 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 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號