Javascript Classes
In ECMA 2015 they added the Class keyword as syntactic sugar over the prior method of created a class through a function and manipulating its prototype.
The clas must be declared before it used.
class Rectangle {
// special keyword function consttuctor
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
// special getter function
get area() {
return this.calculateArea();
}
// normal method
calculateArea() {
return this.w * this.h;
}
// static methods
static distance(r1, r2) {
// calculate distance between two rectangles
}
}
Autoboxing is not supported like it is in prototyping
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
diff() {
return this.y - this.x;
}
}
let p = new Point(2, 3);
p.diff(); // 1
let diff = p.diff();
diff(); // undefined
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.diff = function() {
return this.y - this.x;
}
let p1 = new Point(2, 3);
let diff = p1.diff;
diff(); // 1
You can extend another class and access it with super. You can also extend traditional function-based classes.
class Cat {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Lion extends Cat {
speak() {
super.speak();
console.log(this.name + ' roars.');
}
}
var l = new Lion('Fuzzy');
l.speak();
// Fuzzy makes a noise.
// Fuzzy roars.