var obj = { x: 81, getX: function() { console.log( this.x) } }; var getX = obj.getX.bind(obj);//use obj as 'this'; getX();//81 var getX = function(){ obj.getX.apply(obj); } getX();//also 81
The use of bind and call/apply look very similar, I want to know what's the difference between them.The two getX Function above is the same?
Summary. call : binds the this value, invokes the function, and allows you to pass a list of arguments. apply : binds the this value, invokes the function, and allows you to pass arguments as an array. bind : binds the this value, returns a new function, and allows you to pass in a list of arguments.
Difference between call() and apply() method: The only difference is call() method takes the arguments separated by comma while apply() method takes the array of arguments. Example 1: This example uses call() method to call a function.
The call, bind and apply methods can be used to set the this keyword independent of how a function is called. The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.
So to shortly recap: call is faster than apply because the input parameters are already formatted as necessary for the internal method.
bind
returns a function which will act like the original function but with this
predefined. It is usually used when you want to pass a function to an event handler or other async callback.
call
and apply
will call a function immediately letting you specify both the value of this
and any arguments the function will receive.
Your second example defines an anonymous function which calls apply
. This is a common pattern; bind
provides a standard implementation of that which allows you to do it with a simple function call (thus being quicker and easier to write).
.call()
- calls the same function with the specified arguments
.apply()
- calls the same function with the arguments specified in an array
.bind()
- creates a new function with the same function body, with a preset value of this
(the first argument) and returns that function.
In all cases, the first argument is used as the value of this
inside the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With