Skip to content

Instantly share code, notes, and snippets.

@sukhmeet2390
Last active August 2, 2016 17:58
Show Gist options
  • Save sukhmeet2390/04fcbf8e5e03006b9f92959d2f486ffc to your computer and use it in GitHub Desktop.
Save sukhmeet2390/04fcbf8e5e03006b9f92959d2f486ffc to your computer and use it in GitHub Desktop.
Fixing this in ES5
// ES5 way
var player = {
name : 'Dhoni',
tasks : ['batsman', 'wicket-keeper','fielder'],
printTasks: function(){
this.tasks.forEach(function(task){
console.log(this.name +' is a ' + task);
});
}
};
// this.name is undefined when trying to print it
// ES5 FIX 1: using variable to save the scope
var player = {
name : 'Dhoni',
tasks : ['batsman', 'wicket-keeper','fielder'],
printTasks: function(){
var self = this;
this.tasks.forEach(function(task){
console.log(self.name +' is a ' + task);
});
}
};
// ES5 FIX-2 : using native bind
var player = {
name : 'Dhoni',
tasks : ['batsman', 'wicket-keeper','fielder'],
printTasks: function(){
this.tasks.forEach(function(task){
console.log(this.name +' is a ' + task);
}.bind(this));
}
};
// ES5 FIX-2 : passing context in forEach loop
var player = {
name : 'Dhoni',
tasks : ['batsman', 'wicket-keeper','fielder'],
printTasks: function(){
this.tasks.forEach(function(task){
console.log(this.name +' is a ' + task);
}, this);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment