1

我正在和一个朋友一起构建一个 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;
}());
4

2 回答 2

0

我想到了。它在我的 View 对象中:

var View = (function(){
this.moveView = function(){
            console.log("testing");
    };
var constr = function(f, o, i){
    this.frame = utility.checkFrame(f);
    this.orient = utility.checkOrientation(o);
    /*user identification string*/
    this.id = i;

};
return constr;
}());

我将 moveView 移到 View 对象构造函数之外,不再引发错误。这是一个范围问题。

于 2013-03-11T15:23:42.247 回答
0

如果您的函数在apply()被调用时不存在,那么它在您检查函数的对象中也不存在。

此外,如果f是您的函数参数,list[i].f则不会评估为list[i].yourFunction. 它将永远是list[i].f。您需要检查list[i][f].

于 2013-03-11T15:14:27.337 回答