Apply and Call syntax and invocation

suggest change

The 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

  1. obj will be used as the value of this
  2. forward the arguments to the function
  3. and then return the value

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents