簡體   English   中英

如何執行 JavaScript Function 當我將其名稱作為字符串時(使用具有重載參數的參數)

[英]How to execute a JavaScript Function When I have its name as a string (with parameters that have an overload argument)

我試圖根據我傳入的變量(scamId 和 actorId)調用某個 function,唯一的問題是當我嘗試將 intent2 作為參數傳入時,它似乎沒有從我的存儲庫中找到它需要的東西. 我從如何執行 JavaScript function 中得到了這個小 function 構建器腳本,當我將它的名稱作為字符串傳遞時,我用它來傳遞它的意圖並且我不確定它如何用於其他一些事情,但我不確定它如何工作2,正確創建 function。 它在語句沒有像 if intent2 = "stuff" 那樣重載時起作用,但當我采用以下格式時則不起作用。

例如,如果一切正常,return 語句將等效於 -

return this.intentS1A1Repository.findOne({where: { intent: intentBase }});

    const info = this

    // how can I format this intent2 so that it works?
    const intent2 = { 
      where: 
      { intent: intentBase }
    }

    const getIntent = "intentS" + scamId + "A" + actorId + "Repository.findOne";
    
    await getIntentFunctionBuilder(getIntent, info, intent2);
    
    async function getIntentFunctionBuilder(functionName: string, context: any, args: any) {
      args = Array.prototype.slice.call(arguments, 2);
      var namespaces = functionName.split(".");
      var func = namespaces.pop();
      for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
      }
    
      return await context[func].apply(context, args);  
    }

任何幫助將非常感激!

好吧,我想通了,而不是使用那個瘋狂的 function,它實際上比這簡單得多。

    const intent2 = { 
      where: 
      { intent: intentBase }
    }

    const object = "intentS" + scamId + "A" + actorId + "Repository";
    return await this[object]["findOne"](intent2)

這個小代碼片段可以接受 OVERLOADED PARAMETERS 作為參數,這太棒了。 它允許您傳入自定義構建的函數,因此您不必擁有 20 個不同的函數來執行基本完全相同的任務。 返回的計算結果正是這樣:

return this.intentS*A*Repository.findOne(intent2);

希望您不必通過我試圖弄清楚這一點所做的事情來 go 。 祝你好運。

暫無
暫無

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

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