将 JQuery.append.bind 与匿名函数传递给 Array.forEach 循环的区别

Difference between passing JQuery.append.bind vs anonymous function to a Array.forEach loop

我从中得到了两种不同的行为,我希望有人能解释原因。

function Test( id ) {
           this.target = $(id);
           this.children = [ $('<div/>').text("A"), $('<div/>').text("B") ];
}

// will add 0 1 A B
Test.prototype.addToTarget = function() {
     this.children.forEach(this.target.append.bind(this.target));
};

// will add A B           
Test.prototype.addToTargetEx = function() {            
    var target = this.target;
    this.children.forEach(function(child){
        target.append(child);
    });
};

在第一个版本中,您绑定了 this 值,但是 forEach 将 3 个参数传递给它的回调,即项目、索引和原始数组。

在第二个版本中,您只手动传递给回调的第一个参数,而忽略最后两个。


因此(为了说明问题)您可以强制第二个版本的行为与第一个版本类似...

    this.children.forEach(function(child, idx, arr){
        target.append(child, idx, arr); // Passing all 3 args
    });

现在更清楚 .append() 在每次迭代中接收 3 个值。

使用 .bind() 真的没有任何办法解决这个问题。如果 .append() 只识别传递的第一个参数,那么它就可以工作。


您可以做的一件事是创建您自己的自定义 .bindN 方法。它不能绑定 this 和单个参数,而是可以绑定 this 并接收一个 "limiter",这将限制允许接收的参数数量。

它可能看起来像这样:

Function.prototype.bindN = function(thisArg, n) {
    var origFunc = this;
    return function() {
        return origFunc.apply(thisArg, Array.prototype.slice.call(arguments, 0, n));
    }
};

然后像这样使用它:

this.children.forEach(this.target.append.bindN(this.target, 1));