javascript / intermediate
Snippet
Explicit Binding with call and apply
The call and apply methods allow you to invoke a function while explicitly setting its 'this' context. The difference lies in how they handle arguments: call takes a comma-separated list, while apply takes an array.
snippet.js
1
2
3
4
5
6
function introduce(city, country) {return `${this.name} lives in ${city}, ${country}`;}const person = { name: 'Markus' };console.log(introduce.call(person, 'Berlin', 'Germany'));console.log(introduce.apply(person, ['Vienna', 'Austria']));
Breakdown
1
introduce.call(person, 'Berlin', 'Germany');
Invokes the function with 'this' as 'person' and individual arguments.
2
introduce.apply(person, ['Vienna', 'Austria']);
Invokes the function with 'this' as 'person' and arguments provided as an array.