The call, apply, and bind methods

All functions inherit the call, apply, and bind methods from Function.prototype. We can use these methods to set the value of this.

The call and apply methods are almost identical; both methods allow us to invoke a function and set the value of the this operator within the function. The main difference between call and apply is that, while apply lets us invoke the function with arguments as an array, call requires the function parameters to be listed explicitly.

A useful mnemonic is A (apply) for an array and C (call) for a comma.

Let's look at an example. We will start by declaring a class named Person. This class has two properties (name and surname) and one method (greet). The greet method uses the this ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.