如何将参数添加到存储在稍后调用的数组中的方法中

how to add an argument to a method stored in an array that is called later

本文关键字:调用 数组 方法 参数 添加 存储      更新时间:2023-09-26

这是这个问题的后续(尽管这是自包含的),试图"调用"三个方法,但无法正确使用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