[英]How do I pass a function with arguments to another function to be called?
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
: 但action
是被呼叫上的每个属性都需要另一种说法, 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? 我将如何传递第二个参数,而不必编辑forEachIn
函数? Or should I do something like, pass the possible arguments or parameters in another object or array after action
in the parameters? 还是我应该做一些类似的事情,在对参数进行action
之后,在另一个对象或数组中传递可能的参数或参数?
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. 假定将animations
设置为要使用的动画,这将创建一个闭包。 Note that if animations
might vary during the iteration, you might need to create another closure to capture the value using an IIFE: 请注意,如果animations
在迭代过程中可能有所不同,则可能需要创建另一个闭包以使用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
,则可以将函数绑定到前导参数,仅保留要由forEachIn
迭代提供的设备。
initEquipAnimation : function(animations, equipment) { . . . }
forEachIn(objectList, initEquipAnimation.bind(null, animations));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.