call() method
You can use call()/apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function.So bind() can be used when the function needs to be called later in certain events when it's useful.The function method for manipulating this is call(), which executes the function with a particular this value and with specific parameters. The first parameter of call() is the value to which this should be equal when the function is executed.
In this example, methodName() accepts one parameter that is used as a label to the output value. The function is then called three times. Notice that there are no parentheses after the function name because it is accessed as an object rather than as code to execute.
apply() Method
The apply() method works exactly the same as call() except that it accepts only two parameters: the value for this and an array or array-like object of parameters to pass to the function (that means you can use an arguments object as the second parameter). So, instead of individually naming each parameter using call(), you can easily pass arrays to apply() as the second argument. Otherwise, call() and apply() behave identically. This example shows the apply() method in action
bind() Method
The third function method for changing this is bind(). This method was added in ECMAScript 5.The first argument to bind() is the this value for the new function. All other arguments represent named parameters that should be permanently set in the new function. You can still pass in any parameters that aren’t permanently set later. The following code shows two examples that use bind(). You create the sayMyDatafor1() function by binding the this value to object1, while sayMyDatafor2() binds this to object2 and binds the first parameter as "object2".
Top comments (0)