簡體   English   中英

如何將帶有參數的函數傳遞給另一個要調用的函數?

[英]How do I pass a function with arguments to another function to be called?

具體來說,我有一個遍歷對象文字的函數:

    forEachIn: function(objList, action) {
        for (var thing in objList) {
            if (objList.hasOwnProperty(thing)) {
                action(objList[thing]);
            }
        }
    },

action是被呼叫上的每個屬性都需要另一種說法, animations

    initEquipAnimation: function(equipment, animations) {
        if (typeof equipment !== 'undefined' &&
            equipment !== null) {
            if (equipment.setAnimation) {
                console.log("Setting animation for: " + equipment);
                equipment.setAnimation(animations)
            }
        }
    },

我將如何傳遞第二個參數,而不必編輯forEachIn函數? 還是我應該做一些類似的事情,在對參數進行action之后,在另一個對象或數組中傳遞可能的參數或參數?

第三個參數可能是最簡單的。 如果您不想使用它,則一種可能是傳遞一個參數的函數,然后調用兩個參數的操作方法。

forEachIn(
    objectList,
    function(equipment) { initEquipAnimations(equipment, animations); }
);

假定將animations設置為要使用的動畫,這將創建一個閉包。 請注意,如果animations在迭代過程中可能有所不同,則可能需要創建另一個閉包以使用IIFE捕獲值:

forEachIn(
    objectList,
    (function(anims) {
        return function(equipment) { initEquipAnimations(equipment, anims); }
    }(animations))
);

另一個可能性是,如果您可以靈活地將參數重新排序到initEquipAnimation ,則可以將函數綁定到前導參數,僅保留要由forEachIn迭代提供的設備。

initEquipAnimation : function(animations, equipment) { . . . }

forEachIn(objectList, initEquipAnimation.bind(null, animations));

暫無
暫無

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

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