Apply and Call syntax and invocation
suggest changeThe apply and call methods in every function allow it to provide a custom value for this.
function print() {
console.log(this.toPrint);
}
print.apply({ toPrint: "Foo" }); // >> "Foo"
print.call({ toPrint: "Foo" }); // >> "Foo"
You might notice that the syntax for both invocations above is the same.
apply and call set this; they do not change the function's scope. They also forward arguments:
function speak() {
const sentences = Array.prototype.slice.call(arguments);
console.log(this.name + ": " + sentences.join(" "));
}
const person = { name: "Sunny" };
speak.apply(person, ["I", "Code", "Startups"]); // >> "Sunny: I Code Startups"
speak.call(person, "I", "<3", "JavaScript"); // >> "Sunny: I <3 JavaScript"
Notice that apply allows you to pass an Array or the arguments object (array-like) as the list of arguments, whereas, call needs you to pass each argument separately.
These two methods give you the freedom to get as fancy as you want, like implementing a poor version of the ECMAScript’s native bind to create a function that will always be called as a method of an object from an original function.
function bind (func, obj) {
return function () {
return func.apply(obj, Array.prototype.slice.call(arguments));
}
}
const obj = { name: "Foo" };
function print() {
console.log(this.name);
}
const printObj = bind(print, obj);
printObj();
This will log
“Foo”
The bind function has a lot going on
objwill be used as the value ofthis- forward the arguments to the function
- and then return the value
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents