Monday, December 29, 2014

Overview

Javascript’s new version (EcmaScript 6) has some amazing new features. The one discussed in this post is the new class syntax. More information can be found here.

Details

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// OLD CLASS
var MyObject = function(params){
  this.p1 = params.p1;
  this.p2 = params.p2;
};
// I will go over the new string interpolation in another post
MyObject.prototype.summary = function(){
  return "p1:" + this.p1 + " p2:" + this.p2;
};


// NEW CLASS
class MyObject {
  constructor(p1, p2){
    this.p1 = p1;
    this.p2 = p2;
  }
  summary() {
    return "p1:" + this.p1 + " p2:" + this.p2;
  }
}

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Getters and Setters
class Person {
  constructor(name){
    this._name = name;
  }
  get name(){
    return this._name;
  }
  set name(newName){
    if (newName) {
      this._name = newName;
    }
  }
}

let guy = new Person("Tom");
console.log(guy.name);  // GET - Tom
guy.name = "Steve";     // SET
console.log(guy.name);  // GET - Steve


// Inheritance
class Dev extends Person {
  static allDevs = []
  constructor(name, preferredLang) {
    super(name);
    this.lang = preferredLang;
    Dev.allDevs.push(name);
  }
  static numDevs() {
    return Dev.allDevs.length;
  }
}

Random Posts