22 May 2016

ES6 and beyond - What i really like

Hi dear software companions. It has been a long time. A lot had happened in between. I even changed a residence :)
But enough about me. Let's talk some JavaScript. Recently i have read a book called You Don’t Know JS: ES6 & Beyond written by Kyle Simpson. I was fully overwhelmed with the amount of new features and syntax shortcuts (or how people like to call it syntax sugar) in ES6. Until now i did not have any contact with ES6.
Quite a few things i found interesting. For example one of those things are Proxies.

As i was reading about proxies i realized that many times in the past i was thinking how nice it would be to have structure like this available (together with some kind of syntax for classes which is now also available).
Let's try to define a really simple Proxy in ES6.

As you all probably know, proxy is nothing more than a "stand-in" object, which sits in front of real object. It can do some light-weight work or preparation until the real object is ready or created. Of course there are a lot of applications for proxies and software is full of them. You can easily find a lot of examples and explanations.


In ES6 we define a proxy by passing the original object and handlers. What are these handlers? Handlers are just a list of specially named functions which we can use to do some work. So here is an example for handlers (sometimes called traps) which are invoked when when a property on an object is accessed and when the property is set:

If you run this for example in ES6 Fiddle you should get output like:

So pretty neat stuff. I really like this syntax and feature in ES6. It is clear and handy. I could also not resist using some template strings which also came with ES6.
You are probably wondering now how can you know which named functions are available for handlers. Have a look here at MDN for a complete list of handler traps available to proxy object.
You will often use Proxy and Reflect (introduced also in ES6) in combination. Handlers/traps are called when a meta programming task is executed on an object and the Reflect API is used to execute those tasks directly on the object.

This is all for now. I will post shortly some more on proxies and how they could be used.

No comments:

Post a Comment