我正在和一个朋友一起构建一个 javascript 库,该库应该让 HTML5 游戏创建更容易(但这实际上只是为了好玩),这里有一些我遇到问题的代码:
/* Calls f on all the elems of the list that pass p and implement f */
var apply = function (f, p, list) {
for (var i in list) {
if (p(list[i]) === true && list[i][f] != undefined && typeof list[i][f] === 'function') {
list[i][f]();
}
}
};
this.draw = function(p) {
apply(moveView, p, this.views);
};
用户将调用 this.draw 函数并将谓词传递给它。只有当视图数组中的每个对象都实现了它时,才会执行传递给 apply 函数的函数 moveView。
但是,我的控制台抛出一个错误,提示“未定义 moveView”,这是有道理的,因为 . 在我调用我的应用函数时,我不希望解释器检查 moveView 是否存在,我只想将它传递进去,以便检查每个被应用的对象是否实现了该函数。我认为也许调用 apply likeapply("draw", p, this.views);
会起作用,但那也不起作用,因为在 apply 函数中, f 不再是函数,而是字符串。我真的只是希望能够将任何通用函数名称传递给我的应用函数,这样我就可以在那里进行所有检查。
我所有的代码都可以在我的Github上找到。
编辑:
/*View object*/
var View = (function(){
var constr = function(f, o, i){
this.frame = utility.checkFrame(f);
this.orient = utility.checkOrientation(o);
/*user identification string*/
this.id = i;
this.moveView = function(){
console.log("testing");
};
};
return constr;
}());