TypeScript Language Specification v1.5
TypeScript Language Specification v1.5
TypeScript Language Specification v1.5
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
( id ) => { ... }<br />
( id ) => expr<br />
Thus, the following examples are all equivalent:<br />
(x) => { return Math.sin(x); }<br />
(x) => Math.sin(x)<br />
x => { return Math.sin(x); }<br />
x => Math.sin(x)<br />
A function expression using the function keyword introduces a new dynamically bound this, whereas an<br />
arrow function expression preserves the this of its enclosing context. Arrow function expressions are<br />
particularly useful for writing callbacks, which otherwise often have an undefined or unexpected this.<br />
In the example<br />
class Messenger {<br />
message = "Hello World";<br />
start() {<br />
setTimeout(() => alert(this.message), 3000);<br />
}<br />
};<br />
var messenger = new Messenger();<br />
messenger.start();<br />
the use of an arrow function expression causes the callback to have the same this as the surrounding<br />
'start' method. Writing the callback as a standard function expression it becomes necessary to manually<br />
arrange access to the surrounding this, for example by copying it into a local variable:<br />
class Messenger {<br />
message = "Hello World";<br />
start() {<br />
var _this = this;<br />
setTimeout(function() { alert(_this.message); }, 3000);<br />
}<br />
};<br />
var messenger = new Messenger();<br />
messenger.start();<br />
The <strong>TypeScript</strong> compiler applies this type of transformation to rewrite arrow function expressions into<br />
standard function expressions.<br />
A construct of the form<br />
64