The call() method allows function calls belonging to one object to be assigned and it is called for a different object. It provides a new value of this to the function. The call() method allows you to write a method once and allows it for inheritance in another object, without rewriting the method for the new object.
myFunc.call([thisArg[, arg1, arg2, ...argN]])
- thisArg: The values to use as this when calling myFunc function.
- arg1, arg2, …, argN: These are the arguments for the above mentioned function.
Note: In certain cases, thisArg may not be the actual value. If the method is in non-strict mode, primitive values will be converted to objects and null,undefined will be replaced with the global object.
Return value: It returns the specified this value and arguments as a result of calling of the function.
Example 1: The following example demonstrates the use of calling to chain constructors for an object.
Example 2: The following example demonstrates the use of call() method to invoke an anonymous function.
#0 Peagion: King #1 Crow: Fail
Example 3: The following example demonstrates the use of call method to invoke a function and specifying the context for ‘this’.
Rats typically sleep between 2 and 5 hours
Example 4: The following example demonstrates the use of call() method to invoke a function without specifying the first argument.
string value is Brad
Note: In strict mode, the value of this will be undefined.
Cannot read property 'str' of undefined