JS: Function.prototype.call 👎

By Xah Lee. Date: . Last updated: .
f.call(thisBinding)

Call f with its this (binding) having value of thisBinding.

/*
demo of what Function.prototype.call does.
*/

// define a function that returns the implicit argument this-binding.
function ff() { return this; }

// create a object
const jj = {};

// use ff.call(jj)
console.log(ff.call(jj) === jj);
// true
f.call(thisBinding, arg1, arg2, etc)

Feed f with arguments arg1, arg2, etc.

// example of using Function.prototype.call

function ff(a, b) {
  this.x = a;
  this.y = b;
}

const jj = {};

ff.call(jj, 7, 8);

console.log(jj);
// { x: 7, y: 8 }

Typically, Function.prototype.call is used in a form where the function name is a method of some prototype, like this (Array.prototype.slice).call. It lets you call a method on a object that does not inherit that method.

it's most famously used before 2015 as a way to convert Array-Like Object to Array, like this:

/*
Most famous use of Function.prototype.call is to convert Array-Like Object to Array.
used before 2015.
Like this:
*/
const xalike = { 0: "a", 1: "b", length: 2 };
const xresult = Array.prototype.slice.call(xalike);
console.log(Array.isArray(xresult));
// true

more examples:

console.log(Array.prototype.slice.call(["a", "b", "c", "d", "e", "f", "g"], 0, 3));
// [ "a", "b", "c" ]

console.log(Array.prototype.map.call(["a", "b", "c", "d", "e", "f", "g"], (x) => x + "1"));
// [ "a1", "b1", "c1", "d1", "e1", "f1", "g1" ]

💡 TIP: use Reflect.apply instead. It is clearer and do not rely on prototype chain.

JavaScript. Apply Function