And in addition, you have a function message as shown below:
Now, you have a requirement to pass the person object as the value of this in the function. In addition to explicitly passing the value of this, you also need to pass the value for the age parameter.
You can pass the context (the value of this) explicitly using by either the call() or apply() methods. Consider the following code:
Using the call method, we are passing the object person as the value of this inside message function. You can achieve the same using the apply() method as shown in the listing below:
- The first parameter of both call() and apply() is the value of this object.
- In the call() method, the other arguments to function will be passed as separate comma separated values.
- The call() method takes zero or more individual parameters.
- In the apply() method, the second parameter is an array.
- The apply() method takes an array of parameter.
- You should use the call() method when the number of function parameters is fixed.
- You should use the apply() method, when the number of function parameters is not fixed.