How to apply bind() function in JavaScript?


bind()

unlike apply() function, which gives value as output, Bind() function results in a function that has the ability to execute the code.

If we observe the following code, the apply() function has resulted in value output whereas bind() function resulted in function output.

Example

Live Demo

<html>
<body>
<script>
   var obj = {num : 10};
   var mul = function(i, j, k){
      return this.num * i*j*k;
   }
   var array = [6,3,4];
   document.write(mul.bind(obj,array));
   document.write("</br>");
   document.write(mul.apply(obj,array));
</script>
</body>
</html>

Output

function () { [native code] }
720


In general, when we pass arguments into any function, value output will be displayed. In the same way here, since a function is executed as output, if we try to pass arguments into that function then the value output will be executed.

Example

In the following example, the output function is assigned to a variable called "round" and arguments were passed into that variable so as to get value output instead of function output.

Live Demo

<html>
<body>
<script>
   var obj = {num : 10};
   var mul = function(i, j, k){
      return this.num * i*j*k;
   }
   var array = [6,3,4]
   var round = mul.bind(obj);
   document.write(round(6,3,4));
   document.write("</br>");
   document.write(mul.apply(obj,array));
</script>
</body>
</html>

Output

720
720

Updated on: 30-Jul-2019

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements