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 Freelance Web Developer from Belgium. 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 …)

Leave a comment

Your email address will not be published. Required fields are marked *

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