06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

ECMAScript 6<br />

// with no arguments, single statement<br />

//() => expression;<br />

var f5 = () => 2*2;<br />

console.log(f5()); //4<br />

//IIFE<br />

console.log(( x => x * 3 )( 3 )); // 9<br />

It is important to remember that all the characteristics of a normal function<br />

parameter are available to arrow functions, including default values, destructuring,<br />

and rest parameters.<br />

Arrow functions offer a convenient and short syntax, which gives your code a<br />

very functional programming flavor. Arrow functions are popular because they offer<br />

an attractive promise of writing concise functions by dropping function, return,<br />

and { .. } from the code. However, arrow functions are designed to fundamentally<br />

solve a particular and common pain point with this-aware coding. In normal ES5<br />

functions, every new function defined its own value of this (a new object in case of<br />

a constructor, undefined in strict mode function calls, context object if the function<br />

is called as an object method, and so on). <strong>JavaScript</strong> functions always have their own<br />

this and this prevents you from accessing the this of, for example, a surrounding<br />

method from inside a callback. To understand this problem, consider the following<br />

example:<br />

function CustomStr(str){<br />

this.str = str;<br />

}<br />

CustomStr.prototype.add = function(s){ // --> 1<br />

'use strict';<br />

return s.map(function (a){ // --> 2<br />

return this.str + a; // --> 3<br />

});<br />

};<br />

var customStr = new CustomStr("Hello");<br />

console.log(customStr.add(["World"]));<br />

//Cannot read property 'str' of undefined<br />

On the line marked with 3, we are trying to get this.str, but the anonymous<br />

function also has its own this, which shadows this from the method from line 1. To<br />

fix this in ES5, we can assign this to a variable and use the variable instead:<br />

function CustomStr(str){<br />

this.str = str;<br />

}<br />

[ 178 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!