call, apply And bind Pass Explicit this

call and apply invoke a borrowed method with explicit this (apply takes the argument array), while bind pins this and leading arguments once.

JavascriptResilience

Code

javascriptsnippet
21 lines
// 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));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

One way to read it: the function sizes, doing all the work.

reporter.show reads this.unit, so its output depends on the receiver it is invoked with. reporter.show.call(other, 42) prints count: 42 — call passes this plus individual arguments. reporter.show.apply(other, [7]) prints count: 7, identical except apply takes the argument list as one array. const showCount = reporter.show.bind(other, 0) pre-binds both the receiver and the leading argument, so calling showCount() prints count: 0. The closing sizes function borrows Array.prototype.join on arguments — the classic array-like use — producing 10 | 20 | 30.

Using it

Entry signature: function sizes()

Key statements

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

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `sizes` at load time.