I want to present to you the second part of the blog posts series "ES6 for beginners" written by our dev, Bartosz. You can find the previous part here.
As you can see, two things have changed. First of all, we took out the keyword function, and secondly, we added the Arrow Function ( => ) after the parameters. By some people, it is also called the Fat Arrow Function. This indicates that the arrow is created using an equal sign. An interesting fact is also that there is a so-called thin-arrow in CoffeeScript. It differs in that instead of the equal sign it appears as you probably guess the dash.
We could end here, and I would try to encourage everyone to switch to the new ES6 version. However, if someone wants to know quite an important difference, I encourage you to read a few more lines.
In both of them, we would get what theoretically we want and theoretically how it should be.
I know, I know that's a lot of consoles.logs, but I find it as the best way to figure out what is happening at a given moment. Let's go. First console.log after invoking a doSomeNameMagic method ( myObject.doSomeNameMagic(); ) on the myObject will log us new value of myName. Since a doSomeNameMagic function is attached to the object (same way as myName), this variable will point to the object it is attached. In our case - myObject.
Inside the doSomeNameMagic function, we are doing a little bit more. The changeName function is created and invoked with an argument - "I changed myName once again !". So since we are invoking it let's check the results of 3 console.logs inside it.
The first thing that catches the eye (first line) is that the value this points to a global object, not a myObject. This is how the so-called standalone functions behave. In our case, it will be a browser window object. Since this indicates the window object where there is no information about the variable myName, it should be obvious that the value we get is undefined. The last console.log, however, simply returns the value of the argument passed to changeName.
The next console.log (in IIFE) will also point to the global object for the same reason as above - standalone function, which is simply the so-called IIFE (first picture below). Since in the changeName of the function there was no information about the variable myName, the change failed and the last console.log will simply return the old value (the second image below).
When we decide to solve it using ES6, it is worth knowing how special variable this works. Well, it is quite simple, the Arrow Function does not have its own this value. This value takes on the value of what the Arrow Function is in. So for example, if We wrote a doSomeNameMagic function as an Arrow Function, this would point to ... You guessed - window object. Arrow Functions shine exactly in those moments when anything that requires this to be bound to the context and not the function itself.
In the next post, we will talk about Classes in ES6.