Tuesday, February 2, 2016

Function Bind

Thursday, February 4th 2016

Function.prototype.bind(): 
The method 'bind' of the function class 'binds' the 'this' variable of a function to a particular object. The idea of the 'bind' method is that you can refer to methods that are dependent on contexts that the 'this' keyword simply cannot access, or you could but you would have to create a new file path from the method invocation every time. It essentially fixes variable access to a defined, fixed point in the stack flow state.

this.x = 9; 
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var retrieveX = module.getX;
retrieveX(); // 9, because in this case, "this" refers to the global object

// Create a new function with 'this' bound to module
//New programmers (like myself) might confuse the global var getX with module's property getX
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81

In the example above sourced from MDN, we can see that the boundGetX context is bound to the getX method within the module, thereby referring to the x within module rather than in the global scope. For more, see 'Closure'.

References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/


No comments:

Post a Comment