Last active
August 2, 2016 17:58
-
-
Save sukhmeet2390/04fcbf8e5e03006b9f92959d2f486ffc to your computer and use it in GitHub Desktop.
Fixing this in ES5
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
// 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