Ecmascript 6 (scratchbook)

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:

class doSomething{
 constructor(param){
  this.param = param;
 }

 someMethod(){
   console.log('do something');
 }
}

Really straight forward

Inheritance

Inheritance can be done like so

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

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)

class handler{

constructor(){
 this.node = document.getElementById("somenode");

 this.node.addEventListener("click",(e)=>{this.handler(e)});
}

sayHello(){
 alert('hi!');
}

handler(event){
 this.sayHello() // works;
}

}

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.