Home > Web Front-end > JS Tutorial > Javascript's `bind()`, `call()`, and `apply()`: When Should I Use Each?

Javascript's `bind()`, `call()`, and `apply()`: When Should I Use Each?

DDD
Release: 2024-12-02 01:37:10
Original
126 people have browsed it

Javascript's `bind()`, `call()`, and `apply()`: When Should I Use Each?

Javascript's bind() vs call() and apply(): When to Use Each?

While call() and apply() are both used to invoke functions within a specific context (by setting the this keyword within the function), their primary distinction lies in the way arguments are passed to the function. call() expects arguments to be passed in a comma-separated list, while apply() requires an array of arguments.

Using the bind() Method

Unlike call() and apply(), bind() doesn't invoke the function immediately. Instead, it returns a new bound function that, when later invoked, will have the correct context set for calling the original function. This is particularly useful in situations where you want to maintain the context in asynchronous callbacks or events.

For instance, consider the following code:

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 wouldn't be a MyObject
    //instance as you would normally expect.
};
Copy after login

In the onClick handler, the this keyword will refer to the MyObject instance that created the event listener, even though the event is being triggered asynchronously.

When to Use Call/Apply vs. Bind

Use call() or apply() when you need to invoke a function immediately and modify its context. In contrast, use bind() when you want the function to be callable later with a specific context, such as in events.

Here's a simple illustration:

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
Copy after login

In all three scenarios, the output is 81, since all functions will invoke the getX function within the obj context. However, the bind() version returns a new function that, when executed, will have the desired context set.

The above is the detailed content of Javascript's `bind()`, `call()`, and `apply()`: When Should I Use Each?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template