Home >Web Front-end >JS Tutorial >Javascript `call()` & `apply()` vs. `bind()`: When Should You Use Which?
Javascript: call() & apply() vs bind() Revisited
While call() and apply() allow us to change the context of a function and pass arguments manually or as an array, the bind() method offers a unique approach.
When to Use bind()
Bind is particularly useful when you need to create a function with a predefined context for later execution. Unlike call() or apply(), which invoke the function immediately, bind returns a new function with the specified context set.
The following example demonstrates the difference:
var obj = { x: 81, getX: function() { return this.x; } }; alert(obj.getX.bind(obj)()); // 81 alert(obj.getX.call(obj)); // 81 alert(obj.getX.apply(obj)); // 81
In this example, bind() creates a new function that, when executed, will always have its context set to the obj object. This is particularly valuable in event listeners, where the function context can become ambiguous.
Use Cases
Example:
function MyObject(element) { this.elm = element; element.addEventListener('click', this.onClick.bind(this), false); } MyObject.prototype.onClick = function(e) { var t = this; // do something with [t]... // Without bind, the context of this function would be different. };
Conclusion
Bind allows you to create functions with predefined context, making it particularly useful in event handling, async programming, and other scenarios where maintaining context is crucial. While call() and apply() provide immediate function invocation, bind returns a function for later execution with a fixed context.
The above is the detailed content of Javascript `call()` & `apply()` vs. `bind()`: When Should You Use Which?. For more information, please follow other related articles on the PHP Chinese website!