This page is mainly used for me to add notes on things I encounter while working with EcmaScript 6 in Chrome (48)
Classes:
When working with EcmaScript 6 you can use classes. Classes are defined like so:
1 2 3 4 5 6 7 8 9 |
class doSomething{ constructor(param){ this.param = param; } someMethod(){ console.log('do something'); } } |
Really straight forward
Inheritance
Inheritance can be done like so
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class doSomething{ constructor(param){ this.param = param; } someMethod(){ console.log('do something'); } } class doSomethingDifferent extends doSomething{ constructor(param){ super(param); } someMethod(){ console.log('do something else'); } } var x = new doSomething(); var y = new doSomethingElse(); x.someMethod(); y.someMethod(); |
This
EcmaScript 6 suffers from the same issue with the This keyword as previous versions. So when you have a class in which you add a eventlistener on a node the this in that eventHandler will be the caller (window) and not the class instance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class handler{ constructor(){ this.node = document.getElementById("somenode"); this.node.addEventListener("click",this.handler); } sayHello(){ alert('hi!'); } handler(event){ this.sayHello() // will not work because this will point to the window } } |
Easy solution (source)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class handler{ constructor(){ this.node = document.getElementById("somenode"); this.node.addEventListener("click",(e)=>{this.handler(e)}); } sayHello(){ alert('hi!'); } handler(event){ this.sayHello() // works; } } |