← 中文资源

简体中文版本

call、apply 与 bind 显式传 this

call 与 apply 借用方法并显式指定 this,apply 收参数数组;bind 预绑 this 与前置参数返回新函数,回调不再丢上下文。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

count: 42
count: 7
count: 0
10 | 20 | 30

实现说明

call、apply 与 bind 显式传 this可以归结为函数 sizes。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 sizes。

主要签名是 function sizes()

核心语句

return Array.prototype.join.call(arguments, ' | ');

代码示例

// call / apply 显式传 this:借用不属于对象的方法
const reporter = {
  unit: 'ms',
  show(value) {
    console.log(this.unit + ':', value);
  },
};

const other = { unit: 'count' };
reporter.show.call(other, 42);
reporter.show.apply(other, [7]);

// bind 预绑 this 与前置参数,返回新函数
const showCount = reporter.show.bind(other, 0);
showCount();

// 经典用途:把类数组 arguments 借用数组方法
function sizes() {
  return Array.prototype.join.call(arguments, ' | ');
}
console.log(sizes(10, 20, 30));