[javascript] What is the use of the JavaScript 'bind' method?

Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:

_x000D_
_x000D_
var x = 9; // this refers to global "window" object here in the browser_x000D_
var person = {_x000D_
  x: 81,_x000D_
  getX: function() {_x000D_
    return this.x;_x000D_
  }_x000D_
};_x000D_
_x000D_
var y = person.getX; // It will return 9, because it will call global value of x(var x=9)._x000D_
_x000D_
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81)._x000D_
_x000D_
document.getElementById("demo1").innerHTML = y();_x000D_
document.getElementById("demo2").innerHTML = x2();
_x000D_
<p id="demo1">0</p>_x000D_
<p id="demo2">0</p>
_x000D_
_x000D_
_x000D_

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to bind

Docker Error bind: address already in use Update Angular model after setting input value with jQuery How to remove an appended element with Jquery and why bind or live is causing elements to repeat How to enable named/bind/DNS full logging? What does it mean to bind a multicast (UDP) socket? Detect user scroll down or scroll up in jQuery Cannot assign requested address using ServerSocket.socketBind jQuery bind/unbind 'scroll' event on $(window) What is the use of the JavaScript 'bind' method? Understanding ASP.NET Eval() and Bind()