JS: Function.prototype.call ❌
🟢 TIP: better is Reflect.apply.
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 }
Purpose of Function.prototype.call
This method was added in 1996. It lets you call a method on a object that does not inherit that method. e.g. you have data x, you want to apply a array method on it, but x cannot access array method because it is not a array type.
Typically, Function.prototype.call is used in a form where the function name is a sequence of property chain, like this (Array.prototype.slice).call(args).
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
What's the difference between .call vs .apply
- Function.prototype.call must have each argument as a parameter. (but if you have a array, you can use Spread Operator)
- Function.prototype.apply takes a array for arguments.