ES6 Classes - Node 5.0

'use strict' //required in NodeJS 5.0 to be in strict mode before you use classes class BaseClass { /* Constructor */ constructor(config){ this.config = config; } /* Getter & Setter */ // Using `this._propName` notation for `private` variables get config() { return this._config; } // Merge defaultConfig with config obj passed in in the constructor set config(value){ let defaultConfig = { className: 'BaseClass', classExtends: '', testString: 'Hello World' }; this._config = Object.assign(defaultConfig, value); } /* Methods */ // `String ${variable}` allows you to do string interpolation sayName(){ console.log(`My name is ${this.config.className}.`); } sayTestString(){ console.log(this.config.testString); } /* Static Method */ // Statics can be called without creating a new instance of an object static sayHi(){ console.log('Hi'); } } class ChildClass extends BaseClass { // Constructor constructor(config){ super(config); } // Method sayName(){ console.log(`My name is ${this.config.className}, I extend ${this.config.classExtends}.`) } } /*** Quick Example ***/ var baseClass = new BaseClass(); var childClass = new ChildClass({ className: 'ChildClass', classExtends: 'BaseClass', testString: 'Another Test String' }); BaseClass.sayHi(); // Hi ChildClass.sayHi(); // Hi baseClass.sayName(); // My name is BaseClass baseClass.sayTestString(); // Hello World childClass.sayName(); // My name is ChildClass, I extend BaseClass childClass.sayTestString(); // Another Test String
Quick overview of ES6 Classes, for further info read: https://github.com/lukehoban/es6features#classes.
- This was only tested quickly so if you see any bugs please highlight and I will update it!

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.