簡體   English   中英

將函數/屬性注入另一個函數/對象,可以從該 function 中的函數調用或讀取/設置?

[英]Inject a function/property to another function/object that can be called or read/set from functions within that function?

我可以在 JavaScript 中添加一個 function 到已經存在的 function 或 object 中的 function 然后“突然”可以“看到”並調用自己嗎? 下面是一個例子來演示:

function CreateThing() {
  function callAddedFunction() {
    theFunction(); // this does not exist yet!
  }
}

所以createThing()中顯然不存在theFunction()。 有沒有什么辦法可以在外面添加它,這樣當我調用 callAddedFunction() 時它就可以解決這個問題? 就像是:

let f = new CreateThing();
f.extrafunctions.theFunction = function() {
    console.log("YAY!");
};
f.callAddedFunction();

我曾嘗試使用原型進行試驗,但我一直無法做到這一點。 請注意,我想要這樣做的主要原因是“假”object inheritance 不求助於類和 inheritance,因為這需要在每個 function 調用前使用 this 關鍵字。 我還想避免必須在該 function 中傳遞一個 object 作為可以調用以達到其他功能的參數。 我知道我可以通過在全局 scope 中擁有所有這些額外功能來實現這一點,但我希望盡可能避免這種情況。

以防萬一OP ...

我不確定這正是您想要的,但您也可以使用通用的高階 function 返回您正在尋找的實現。

 const supplimentor = (src, extraFunc) => ({ src: new src(), extraFunc }) //OR function supplimentor1(src, extraFunc) { this.extraFunc = extraFunc; new src(); } function CreateThing() {console.log('SOURCE')} const extraFunc = () => console.log('EXTRA'); const newFunc = supplimentor(CreateThing, extraFunc) newFunc.extraFunc() const newFunc1 = new supplimentor1(CreateThing, extraFunc) newFunc1.extraFunc()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM