实现说明
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));