ES6 Fat Arrow => Quirks

Along with our tech update push, we're looking to start using/supporting ES6 in our codebase.

It happens to be that the Fat Arrow syntax => has a couple of quirks that stood out to me.

'This' Binding

For arrow functions, this is lexically bound and not dynamically set. It doesn't create its own execution context, but takes this from the outer function where it is defined.

One thing to keep in mind, is that in Javascript, scope defined by functional scope.

Example 1:

When using a regular function, the this binding on event listeners is normally set to the element that triggered the event.

But since the Arrow function is called in the global context, this is bound to Window.

document.addEventListener('click', function() {  
   console.log(this);
   //#document
});

document.addEventListener('click', () => console.log(this));  
//Window {...}

Example 2:

Even though process is a method called on the invoice object, since invoice was created in the global scope, it will always be bound to window.

var invoice = {  
number: 123,  
process: () => console.log(this)  
};

invoice.process();  
//Window {...}

Example 3:

process is now method using a regular function, which binds this to the invoice object that invoked it.

Since the Arrow function lives within this new functional scope of the invoice Object, the this binding of the Arrow function is also the invoice Object.

var invoice = {  
number: 123,  
process: function(){return () => console.log(this);}  
};

invoice.process()();  
//Object {number: 123}

Example 4:

.bind(), .call() and .apply() do not modify the this binding of Arrow functions.

var invoice = {  
number: 123,  
process: function(){return () => console.log(this.number);}  
};

var newInvoice = {  
number: 222  
};

invoice.process().bind(newInvoice)(); //123  
invoice.process().call(newInvoice); //123  
invoice.process().apply(newInvoice); //123  

No Prototype Object

Regular functions function () {...} have a prototype property that is used for creating constructor functions and attaching methods to the prototype.

Arrow functions don't have this prototype property.

var getVal = () => 123;  
console.log(getVal .hasOwnProperty('prototype'));  
//false

Duncan Leung

Front End Developer at iHerb.com

Irvine, CA

Subscribe to Duncan Leung: Javascript and Front End Development

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!