Simple object with the method
The above example will output result “johndoe” because this keyword points to the current object and have properties “firstName” and “lastName”
Now let’s come to call() method part.
Syntax: obj.callingMethod.call(anotherObject, callingMethodArg1, callingMethodArg2….);
call() method is used for calling any object method with some arguments contains another object along with called function arguments. Please check the following example of call() method
In this example, I just passed another object which is containing the same properties “firstName” and “lastName” so now this refers to the nameObj object in getName() method.
Now let’s see the call() arguments
In the upper example, getAddress() function can have two arguments city and country so I can pass calling function arguments as well.
let’s see a different function which returns the only sum of two numbers
Syntax: obj.callingMethod.apply(anotherObject, arrayofArguments);
apply() method is used for calling any object method with some arguments contains another object along with called function arguments as an array.
this method is very similar to call() but the only difference it takes called function arguments as an array instead of passing one by one. Please see the following example of finding maximum or minimum value in an array.
You can practice upper examples of call() method as well.
I hope you had some basic idea of call() and apply() methods. You can now differentiate between call() and apply(). Thanks for your time.