ES6 ES2015 Arrow Functions and this

Why you’d want to use arrow functions (next to them being shorter to type):

Arrow functions will maintain the this value of the enclosing context

Yes, this will work just fine:

function Wilto() {
	this.age = 32;

	setInterval(() => {
		this.age++;
		console.log( "I am now " + this.age + " years old");
	}, 3000 );
}

Whereas we used to do stuff like this:

function Wilto() {
	var self = this;
	self.age = 32;

	setInterval( function constantBirthdays() {
		self.age++;
		console.log( "I am now " + self.age + " years old");
	}, 3000 );
}

Source: A List Apart: On Our Radar: Self-Centered Edition →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.