gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:24:34 30 4
gpt4 key购买 nike

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

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);
});
};

最佳答案

在第一个版本中,您绑定(bind) this 值,但 forEach 将 3 个参数传递给其回调,分别是项目、索引和原始数组.

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

<小时/>

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

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

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

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

<小时/>

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

它可能看起来像这样:

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));

关于javascript - 将 JQuery.append.bind 与匿名函数传递给 Array.forEach 循环之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29462180/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com