0

我一直在尝试为更小的插件模仿一些 jQuery 的语法。一段时间以来,我一直在努力在内部使用 $ 对象的方法。让我举例说明:

(function() {
    window.$ = function (element) {
        return new Plugin(element);
    };

    var Plugin = function (element) {
        this.element = element;
    };

    Plugin.prototype = {
        foreach: function(callback) {
            // Of course the "foreach" function will be bigger than this, this is just for testing.
            var values = [];
            for (i = 0; i < this.element.length; i++) {
                values[i] = callback.call(this, this.element[i], i);
            }

            return values;
        },
        someOtherFunctionThatUsesForeachInternally: function() {
            var arr = [];
            $([6, 32, 2]).foreach(function(item, key) {
                arr[key] = item + 7;
            });
            return arr;
        }
    };
})();

/* Desired result: 
[
    [13, 39, 9],
    [13, 39, 9],
    [13, 39, 9],
    [13, 39, 9]
]
*/

var arr = [1, 5, 7, 9];
var test = [];

$(arr).foreach(function(value, key) {
    test[key] = this.someOtherFunctionThatUsesForeachInternally();
});

console.log(test);

每当美元符号与参数(例如数组,在示例中 this 为var arr = [1, 5, 7, 9])结合使用时,都会实例化一个新的 Plugin 对象,然后立即调用一个方法。

我写了一个小foreach程序来测试,但似乎不可能从框架内的函数调用它。console.log(test);最后将输出 [[13, 39, 9]],而不是为 var arr 的每个元素执行此操作。我猜这是因为this在内部调用 foreach 时会被覆盖。

关于如何解决这个问题的任何想法?

4

1 回答 1

1

方法中的for循环索引 ( i)foreach被覆盖,因为您已在全局范围内声明它。总是var用来声明变量:

for (var i = 0; i < this.element.length; i++) {
    values[i] = callback.call(this, this.element[i], i);
}

演示:http: //jsfiddle.net/QhXa7/

于 2013-05-17T14:06:19.770 回答