Use JS es6 on your NodeJS app
suggest changeES2015 (also called ES6) added syntax for classes, arrow functions, and other everyday tasks.
Prerequisites:
- Check out the new es6 features at http://es6-features.org - it may clarify to you if you really intend to use it on your next NodeJS app
- Check the compatibility level of your node version at http://node.green
- If all is ok - let’s code on!
Here is a very short sample of a simple hello world app with JS es6
'use strict'
class Program
{
constructor()
{
this.message = 'hello es6 :)';
}
print()
{
setTimeout(() =>
{
console.log(this.message);
this.print();
}, Math.random() * 1000);
}
}
new Program().print();
Run it and the same message prints again and again, because print schedules itself.
Line by line:
'use strict'
'use strict' is not what turns ES2015 on. A class body is already strict. Strict mode does change other semantics. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode.
class Program
class is syntax on top of the same prototypes. Before ES2015 the usual pattern was a constructor function:
function MyClass() // class definition
{
}
var myClassObject = new MyClass(); // generating a new object with a type of MyClass
When using OOP, a class is a very fundamental ability which assist the developer to represent a specific part of a system (breaking down code is crucial when the code is getting larger.. for instance: when writing server-side code)
constructor()
{
this.message = 'hello es6 :)';
}
You got to admit - this is pretty intuitive! This is the c’tor of my class - this unique “function” will occur every time an object is created from this particular class (in our program - only once)
print()
{
setTimeout(() => // this is an 'arrow' function
{
console.log(this.message);
this.print(); // here we call the 'print' method from the class template itself (a recursion in this particular case)
}, Math.random() * 1000);
}
Because print is defined in the class scope - it is actually a method - which can be invoked from either the object of the class or from within the class itself!
So.. till now we defined our class.. time to use it:
new Program().print();
Which is truly equals to:
var prog = new Program(); // define a new object of type 'Program'
prog.print(); // use the program to print itself
In conclusion: JS es6 can simplify your code - make it more intuitive and easy to understand (comparing with the previous version of JS).. you may try to re-write an existing code of yours and see the difference for yourself
ENJOY :)