2804. call vs apply vs bind
2025年6月25日小于 1 分钟
2804. call vs apply vs bind
Problem: 2804. 数组原型的 forEach 方法
/**
* apply
*/
Array.prototype.forEach = function (callback, context) {
const values = this;
for (let i = 0; i < values.length; i++) {
callback.apply(context, [values[i], i, values])
}
}
/**
* call
*/
Array.prototype.forEach = function (callback, context) {
const values = this;
for (let i = 0; i < values.length; i++) {
callback.call(context, values[i], i, values)
}
}
/**
* bind 参数可以预绑定
*/
Array.prototype.forEach = function (callback, context) {
const values = this;
for (let i = 0; i < values.length; i++) {
callback.bind(context, values[i], i, values)();
}
}
Array.prototype.forEach = function (callback, context) {
const values = this;
for (let i = 0; i < values.length; i++) {
callback.bind(context)(values[i], i, values);
}
}
Array.prototype.forEach = function (callback, context) {
const values = this;
for (let i = 0; i < values.length; i++) {
callback.bind(context,values[i], i)( values);
}
}
方法 | 描述 | 是否立即执行 | 是否返回新函数 | 参数格式 |
---|---|---|---|---|
call | 使用指定的 this 值和若干参数调用函数 | ✅ 是 | ❌ 否 | 逗号分隔参数 |
apply | 使用指定的 this 值和参数数组调用函数 | ✅ 是 | ❌ 否 | 参数数组 |
bind | 返回一个绑定了 this 和部分参数的新函数 | ❌ 否 | ✅ 是 | 逗号分隔(可预绑定) |