Skip to content

Instantly share code, notes, and snippets.

@pablodenadai
Created February 8, 2017 05:57
Show Gist options
  • Save pablodenadai/3964bd2cd8de63af1b4ae920843b5d68 to your computer and use it in GitHub Desktop.
Save pablodenadai/3964bd2cd8de63af1b4ae920843b5d68 to your computer and use it in GitHub Desktop.
.bind - JavaScript
/**
* 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