Skip to content

Instantly share code, notes, and snippets.

@MacKentoch
Last active December 16, 2015 13:48
Show Gist options
  • Save MacKentoch/e33bdf0a2df6bd042149 to your computer and use it in GitHub Desktop.
Save MacKentoch/e33bdf0a2df6bd042149 to your computer and use it in GitHub Desktop.
this is tricky
var hello= 'bonjour';
var will = {
hello : 'hello',
tab : [1,2],
say : function(){
console.info(this.hello)
},
iterateSay : function(){
this.tab.every(function(value, index){
console.info(this.hello);
return false;
})
//solution to keep this context : bind to expected this
//this.tab.every(function(value, index){
// console.info(this.hello);
// return false;
//}.bind(this))
}
}
//borrowed function
var test = will.say;
console.info(will.say()); //say : 'hello' - will context as expected
console.info(test()); //this when in a borrowed function won't execute in same context
//solution :
//console.info(test.call(will));
//closure
will.say(); //say : 'hello' - will context as expected
will.iterateSay(); //this when in a closure function execute in global context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment