Skip to content

Instantly share code, notes, and snippets.

@wklug
Last active October 27, 2016 03:42
Show Gist options
  • Save wklug/642b98c4b678f4ae84466b39a4a5fb3e to your computer and use it in GitHub Desktop.
Save wklug/642b98c4b678f4ae84466b39a4a5fb3e to your computer and use it in GitHub Desktop.
ES6 - Arrow functions working with "this"
/**
* ES6 - Arrow functions.
*
* Arrow functions don't rebind `this`. Comparison between old `function` approach and `arrow function` approach.
**/
function Person0(name, age) {
this.name = name;
this.age = age;
setTimeout(function() {
this.age += 10;
console.log(this.name + ' grew up. He is ' + this.age + ' years old, now!'); // grew up. He is NaN years old, now!
}, 1000);
}
var PeterNutt = new Person0('P. Nutt', 18);
function Person1(name, age) {
self = this;
self.name = name;
self.age = age;
setTimeout(function() {
self.age += 10;
console.log(self.name + ' grew up. He is ' + self.age + ' years old, now!'); // P. Nutt grew up. He is 28 years old, now!
}, 1000);
}
var PatrickNutt = new Person1('P. Nutt', 18);
function Person2(name, age) {
this.name = name;
this.age = age;
setTimeout(() => {
this.age += 10;
console.log(this.name + ' grew up. He is ' + this.age + ' years old, now!'); // P. Nutt grew up. He is 28 years old, now!
}, 1000);
}
var ParkerNutt = new Person2('P. Nutt', 18);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment