.bind in javascript code example
Example 1: what is the use of bind method in javascript
"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.
code:
var x = 9; // this refers to global "window" object here in the browser
var person = {
x: 81, // local variable x = 81
getX: function() {
return this.x; // "this" = person , so this.x is the same as person.x
}
};
// the next line of code is the most important one (line 17)
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
var myFunc = 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).
y(); // return 9 (the global variable);
myFunc();"
Example 2: bind in javascript
bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function.
Example 3: javascript bind this syntax
func.bind(this)
Example 4: javascript bind
function myFunc(p1, p2, pN, addedParam)
{
}
let myThis = {};
let f = myFunc.bind(myThis, "param1", "param2", "paramN");
f("addedParam");