Skip to content

Instantly share code, notes, and snippets.

@cosminnicula
Created July 11, 2012 11:07
Show Gist options
  • Save cosminnicula/3089716 to your computer and use it in GitHub Desktop.
Save cosminnicula/3089716 to your computer and use it in GitHub Desktop.
A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this
//Varint 1: use bind function https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
var val = 1;
var myObject = {
val: 11,
getVal: function() { return this.val; }
};
console.log(module.getVal()); // 11
var getVal = myObject.getVal;
console.log(getVal()); // 1, because in this case, "this" refers to the global object
// create a new function with 'this' bound to myObject
var boundGetVal = getVal.bind(myObject);
console.log(boundGetVal()); // 11
//Varint 2: alternative to bind function
val = 2;
myObject = {
val: 22
}
myObject.getVal = function() {
var that = this;
var helper = function () {
console.log(that.val);
};
helper();
}
myObject.getVal(); // 22, because although the function is called from the global context, there is a closure in the getVal function in which "that" is bound to myObject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment