如何将参数添加到存储在稍后调用的数组中的方法中
how to add an argument to a method stored in an array that is called later
这是这个问题的后续(尽管这是自包含的),试图"调用"三个方法,但无法正确使用jQuery映射。
我试图将一组方法存储在数组中,但有一组方法可能具有如下参数(初始方法在before_methods中,建议的方法在lm_method中)。我确信我想要什么是不言自明的,但我希望能够将参数合并为对f的合理调用(特别是arc.pLikedByTerm)
// signature
pLikedByTerm:function(term, ne, sw, m){
....
}
// code before_methods just to show
this.before_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems];
this.lm_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedItems, arc.pLikedByTerm('surfing'),arc.pLikedByTerm('sailing')];
$.each(this.lm_methods, function(i,f){
f(ne,sw,m);
});
我该怎么做,还是这个设计不好?惯用的方法是什么?我的大脑被炸了。
thx提前
更新1
玩下面的答案,看起来这可能是最简单的事情:
var fns=[logStuff("this is msg"), logMoreArgs("a term","a you msg")];
for (var i=0; i<fns.length; i++) {
fns[i];
}
当经常使用时,拥有一个函数数组是一种常见的做法。例如,考虑这个回调类。
function Callback(){
this.callbacks = [];
}
Callback.prototype.run = function(cb) {
for (var i=0; i<this.callbacks.length; i++) {
this.callbacks[i]();
}
};
然后我们可以添加一些回调。
function logStuff(msg) {
jsprint(msg || "No message");
}
obj = new Callback();
obj.callbacks.push(logStuff);
obj.callbacks.push(logStuff);
obj.run();
如果我们运行这个,我们会发现它只记录了我们的默认值。因此,如果我们想绑定一些数据,我们可以使用bind函数。
函数.prototype.bind
thisArg
要作为this参数传递给目标的值函数。如果绑定函数是使用新的运算符构造的。arg1、arg2
在提供给绑定函数的参数前面加上的参数当调用目标函数时。
我们的新代码将第一个参数设置为不同的字符串,然后我们可以看到这些字符串。您可以绑定任意数量的参数。
obj = new Callback();
obj.callbacks.push(logStuff.bind(null, "My message"));
obj.callbacks.push(logStuff.bind(null, "My other message"));
obj.run();
最终结果
这样做还可以。只需删除参数和parens:
代替:
this.lm_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedAItems,arc.pLikedByTerm('surfing'),arc.pLickedByterm('siling')];
Do:
this.lm_methods=[arc.pLocations,arc.pLikedLocations,arc.pLikedAItems,arc.pLikedByTerm,arc.pLickedByTerm];
示例:
function say(txt) {
console.log("say" + txt);
}
function shout(txt) {
console.log("shout" + txt);
}
function whisper(txt) {
console.log("whisper" + txt);
}
var funcArr = [say, shout, whisper];
$.each(funcArr, function(i, f) {
f("hello");
});
将打印:
说你好shouthiswhispermhello
- D3-如何为工具提示调用数组
- Asp.net将代码背后的数据传递给Javascript并调用数组
- 完成ajax调用数组的循环,而不是在某个调用出错时中断
- 构建Ajax调用数组时,JQueryAjax成功回调不起作用
- 需要帮助调用数组以在Html中发布
- jQuery,从变量调用数组对象的一部分
- 在循环中调用数组的索引导致错误
- 如何使用 jQuery 调用数组
- 如何调用数组的字符串进行显示
- 从另一个网页调用数组
- 在调用数组的映射函数时丢失它
- Javascript序列与函数调用数组
- 在输入字段中调用数组值
- 如何调用数组概念$mbAudio
- 如何使用jade中的变量调用数组'
- 如何调用数组中的一段数字
- 从HTML输入值调用数组
- 在JavaScript的另一个函数中调用数组
- 在jQuery中动态调用数组名
- 在函数中动态调用数组