Created
February 8, 2017 05:57
-
-
Save pablodenadai/3964bd2cd8de63af1b4ae920843b5d68 to your computer and use it in GitHub Desktop.
.bind - JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The bind() method creates a new function that, when called, | |
* has its this keyword set to the provided value, | |
* with a given sequence of arguments preceding any | |
* provided when the new function is called. | |
*/ | |
this.x = 9; // this refers to global "window" object here in the browser | |
var module = { | |
x: 81, | |
getX: function() { return this.x; } | |
}; | |
module.getX(); // 81 | |
var retrieveX = module.getX; | |
console.log(retrieveX()); | |
// returns 9 - The function gets invoked at the global scope | |
// Create a new function with 'this' bound to module | |
// New programmers might confuse the | |
// global var x with module's property x | |
var boundGetX = retrieveX.bind(module); | |
console.log(boundGetX()); // 81 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment