Let's now look at the apply
method for context
binding. It works in much the same way as the call
method. The difference is that in apply, the parameters
are passed as an array, rather than listed with a comma.
Depending on the task, one or the other method is
convenient.
Here is an example of passing parameters to the apply method:
func.apply(elem, [param1, param2]);
Let the following code be given:
<input id="elem" value="hello">
let elem = document.querySelector('#elem');
function func(surname, name) {
console.log(this.value + ', ' + surname + ' ' + name);
}
func(); // should output here 'hello, John Smit'
Add the apply
method to the last line so
that 'hello, John Smit'
is displayed. The
word 'hello'
must come from the value input,
'John'
and 'Smit'
must be function
parameters.