Javascript Function bind() Method Explained

$$/$$

In the next video, let’s look at one of the problems with the ‘this’ keyword which you have already seen earlier. This problem was related to having issues with the ‘this’ keyword pointing to the global object inside a function call defined inside a method rather than pointing to the object inside which the function (regular function) is defined. After looking at the problem, you’ll also look at how you can solve it.

$$/$$

In the last video, you looked at how you can make the ‘this’ keyword point to the object inside a function which is defined inside a method of the object. You could do that by assigning the context ‘this’ to another variable inside the method and then access this variable inside the function defined in the method.

However, there’s a better solution to solve this problem. Let’s look at this solution in the next video.
 

$$/$$

In the last video, you looked at how you can solve the problem of making the ‘this’ keyword point to the object inside a function defined in the method of the object using the bind() method. This method actually binds the passed scope to the function. Two important points to be noted about the bind() method:

  1. You can pass any context to the bind() method. This is the first argument of the bind() method. Whatever is passed as the context, the ‘this’ keyword inside the function to which the bind() method is applied, starts pointing to the passed context.
     
  2. You can also pass other arguments to the bind() method. But note that the first argument must always be the context. The rest of the arguments can be anything that the bind() method takes and the function, to which the bind() method is applied, accepts in parameters.

 

Apart from the bind() method, we also have other methods in JavaScript using which, you can solve this problem of the ‘this’ keyword. Let’s look at one more such method in the next segment.