Вопрос

To be specific, I have one function that iterates through an object literal:

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

But the action that's being called on each of the property requires another argument, animations:

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

How would I go about passing that second argument, without having to edit the forEachIn function? Or should I do something like, pass the possible arguments or parameters in another object or array after action in the parameters?

Это было полезно?

Решение

A third argument might be simplest. If you don't want to use that, one possibility is to pass a function of one argument that then invokes the two-argument action method.

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

This creates a closure assuming that animations is set to the animations to be used. Note that if animations might vary during the iteration, you might need to create another closure to capture the value using an IIFE:

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

Another possibility is, if you have the flexibility of reordering the arguments to initEquipAnimation, is to bind the function to the leading arguments, leaving only the equipment to be supplied by the forEachIn iteration.

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

forEachIn(objectList, initEquipAnimation.bind(null, animations));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top