Function Expressions vs Arrow Functions
JS
S
JavaScriptSome clarifications over the differences between function expressions and arrow functions and why sometimes is more useful to use a function expression (any JS environment, either browser or Node.js). The value of `this` is determined by how a function is called. Arrow functions are useful if you NEED to access the context of the current environment. It is not possible to set an arrow function's this with .bind or .call. Rules: Replace a function expression with an arrow function if: a) Functions that don't use this or arguments. b) Functions that are used with .bind(this) Do not replace if: a) It's a constructor function b) Function / methods added to a prototype (because they usually use this)
1// Basic Example
2var test = {
3 prop: 42,
4 func: () => {
5 return this.prop;
6 },
7};
8test.func(); // undefined
9
10var test = {
11 prop: 42,
12 func: function() {
13 return this.prop;
14 },
15};
16test.func(); // 42
17
18
19// Function expression as an object factory
20// Context is objectFactory return object
21function objectFactory() {
22 console.log('Inside `objectFactory`:', this.views);
23 return {
24 views: 0,
25 play: function() {
26 console.log('Inside `play` function:', this.views);
27 },
28 };
29}
30
31objectFactory.call({views: 7}).play(); // override `this`
32// Inside `objectFactory`: 7
33// Inside `play`: 0
34
35
36// Arrow Function Version
37// Context is 'this' of objectFactoryAf
38function objectFactoryAf() {
39 console.log('Inside `objectFactoryAf`:', this.views);
40 return {
41 views: 42,
42 play: () => console.log('Inside `play`:', this.views),
43 };
44}
45objectFactoryAf.call({views: 21}).play(); // override `this` inside objectFactoryAf
46// Inside `objectFactory`: 21
47// Inside `play`: 21Created on 5/17/2018