ES2015 Arrow Functions

by Owain Stratton

JavaScript

// Shorter syntax example
const fruits = [
	'Apple',
	'Orange',
	'Pear',
	'Grapefruit',
	'Banana'
];

const array1 = fruits.map(function(fruit) { return fruit.length }); 
const array2 = fruits.map( fruit => fruit.length ); // Notice that we are not required to declare 'return' 


// -------------------------------------------------------------
// -------------------------------------------------------------


// Not binding 'this'


function Shop1() {
	let that = this;
	that.items = 100;
	
	setInterval(function buyItems() {
		// The callback refers to the `that` variable of which
		// the value is the expected object.
		that.items--;
		console.log('Shop1', this);
		console.log('Shop1', that);
  	}, 1000);
}
// const startShopping = new Shop1();


function Shop2() {
	this.items = 100;
	
	setInterval(() => {
		this.items--;
		console.log('Shop2', this);
  	}, 1000);
}
// const startShopping = new Shop2();