Last active
January 3, 2016 06:28
-
-
Save harry1989/8422384 to your computer and use it in GitHub Desktop.
Binding this in 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
When we have any asynchronus code that tries to access the object patterns, we run into issues with javascript `this` issue. | |
Ex: | |
var harry = { 'name': 'harry', | |
'greet' : function(){console.log('Hello ' + this.name)}, | |
'print' : function(){ | |
// using setTimeout, it can be any async function | |
setTimeout(this.greet, 1000); // this will fail! | |
} | |
When the below code runs.. | |
harry.print() | |
after a second, this will be ponting to javascript window(global object), to get it working we earlier used the below patter. | |
var that = this; | |
var harry = { 'name': 'harry', | |
'greet' : function(){console.log('Hello ' + this.name)}, | |
'print' : function() { | |
var that = this; | |
setTimeout(that.greet, 1000); | |
} | |
this works, but not intuitive when we can use fn.bind | |
the new code looks like below.. | |
var harry = { 'name': 'harry', | |
'greet' : function(){console.log('Hello ' + this.name)}, | |
'print' : function() {; | |
setTimeout(this.greet.bind(this), 1000); | |
} | |
or | |
var harry = { 'name': 'harry', | |
'greet' : function(){console.log('Hello ' + this.name)}, | |
'print' : function() {; | |
setTimeout(function(){ | |
this.greet(); | |
}.bind(this), 1000); | |
} | |
The value of 'this' gets binded to where the function is invoked but not where it is defined. | |
What lies ahead? | |
Well with the new ECMAScirpt function, you can use the arrow lexical binding which automatically takes care of binding the this within the function. | |
var harry = { 'name': 'harry', | |
'greet' : function(){console.log('Hello ' + this.name)}, | |
'print' : function() { | |
setTimeout(() => { | |
this.greet(); | |
}, 1000); | |
} | |
Reference: | |
* http://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/ | |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment