Javascript Interview - bind function

The bind() function is a method available on all function objects in JavaScript.It returns a new function, where the value of this is bound to the argument passed into bind().

  • You have a function, and within that function, you use this.

function test() {
         console.log(this.first_name);
 }        

this is not defined within the scope of test(). In non-strict mode, this would default to the global object (window in a browser). In strict mode, this would be undefined.

  • You have an object with a property first_name.

let obj = {
  first_name: 'Hello, world!'
};        

You want this within test() to refer to obj. You can achieve this by using bind().

let bound = test.bind(obj);
boundFunction();        

Now, it logs 'Hello, world!'.

the bind() method is particularly useful in scenarios where the context of this changes, such as in event handlers, timeouts, or any other callbacks. By using bind(), you can control what this refers to, regardless of where or how the function is called.

Feel free to comment on more useful resources and content.

To view or add a comment, sign in

More articles by Ajay Sharma

  • Javascript - String Literal

    String literal is sequence of characters enclosed in single quotes ( ' ), double quotes ( " ) and backticks ( ` ). We…

    1 Comment

Explore content categories