5. What is call function?

call invoked on a function allows to pass an object, which will be used as this. It loads context of the function

call is different from bind - in call function is invoked immediately with parameters passed as a second and subsequent arguments of call. These argument will be passed to function in the same order.

const person = { firstName: 'Mario', print: function(arg1, arg2) { console.log(`I'm ${this?.firstName} and this is an arg1: ${arg1} and arg2: ${arg2}`); } }; person.print() // I'm Mario and this is an arg1: undefined and arg2: undefined const printFunction = person.print; printFunction(); // I'm undefined and this is an arg1: undefined and arg2: undefined printFunction.call(person); // I'm Mario and this is an arg1: undefined and arg2: undefined printFunction.call(person, "arg1", "arg2"); // I'm Mario and this is an arg1: arg1 and arg2: arg2

call is different from apply - in call arguments passed to function are separated with comma, while in apply it's an array of arguments.

printFunction.call(person, "arg1", "arg2"); // I'm Mario and this is an arg1: arg1 and arg2: arg2 printFunction.apply(person, ["arg1", "arg2"]); // I'm Mario and this is an arg1: arg1 and arg2: arg2
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.