JavaScript's bind, call, and apply Functions
Learn how to override the this variable in JavaScript functions using bind, call, and apply, including strictBindCallApply.
Introduction to strictBindCallApply
option
JavaScript provides the bind
, call
, and apply
functions that are used to override the value of the this
variable inside a function. When using the bind
, call
, and apply
functions, we essentially provide a particular version of the object that the function
should use as the value for this
and then invoke the function with the parameters it requires. The strictBindCallApply
option ensures that we provide these function parameters with the correct types.
To illustrate this concept, consider the following code:
class MyBoundClass {name: string = "defaultNameValue";printName(index: number, description: string) {console.log(`this.name : ${this.name}`);console.log(`index: ${index}`);console.log(`description : ${description}`);}}
Here, we have a class definition for a class named MyBoundClass
that has a name property of type string
and a function called printName
. The printName
function has two parameters, named index
of type number
and description
of type string
.
The printName
function logs three messages to the console:
- The first log outputs the value of the
name
property, using the syntaxthis.name
. - The second log outputs the
value of the
index
parameter. - The third log outputs the value of the
description
parameter.
We can now use this class as follows:
let testBoundClass = new MyBoundClass();testBoundClass.printName(1, "testDescr");
Here, we have created an instance of the class MyBoundClass
, and assigned it to
a variable named testBoundClass
. We then call the printName
function with the arguments of 1
and testDescr
.
Here, we can see that the output matches our expectations. The value of the internal name
property is the value defaultNameValue
, and the values of the index
and description
arguments are what were passed into the printName
function.
Using the call
function
Using the JavaScript call
function, however, we can modify the value of the this
variable.
Consider the following call to the printName
function:
testBoundClass.printName.call({ name: `overridden name property` }, 1, `whoa !`);
Here, we invoke the printName
function on ...