We’re going from enhanced object literals that look a lot like classes to actual classes in ES6. We’ll learn, however, that these aren’t really classes, but syntactic sugar over the existing prototype functions in JavaScript. Let’s continue on with the Learning ES6 series series!
TL;DR
ECMAScript 6 provides syntactic sugar over the prototype-based, object-oriented pattern in JavaScript. ES6 classes provide support for constructors, instance and static methods, (prototype-based) inheritance, and super calls. Instance and static properties are not (yet) supported.
// Define base Note class
class Note {
constructor(id, content, owner) {
this._id = id;
this._content = content;
this._owner = owner;
}
static add(...properties) {
// `this` will be the class on which
// `add()` was called increment counter
++this._idCounter;
let id = `note${this._idCounter}`;
// construct a new instance of the note passing in the
// arguments after the ID. This is so subclasses can
// get all of the arguments needed
let note = new this(id, ...properties);
// add note to the lookup by ID
this._noteLookup[id] = note;
return note;
}
static get(id) {
return this._noteLookup[id];
}
// read-only
get id() { return this._id; }
get content() { return this._content; }
set content(value) { this._content = value; }
get owner() { return this._owner; }
set owner(value) { this._owner = value; }
toString() {
return `ID: ${this._id}
Content: ${this._content}
Owner: ${this._owner}`;
}
}
// Static "private" properties (not yet supported in class syntax)
Note._idCounter = -1;
Note._noteLookup = {};
class ColorNote extends Note {
constructor(id, content, owner, color='#ff0000') {
// super constructor must be called first!
super(id, content, owner);
this._color = color;
}
get color() { return this._color; }
set color(value) { this._color = value; }
toString() { // computed method names are supported
// Override `toString()`, but call parent/super version
// first
return `${super.toString()}
Color: ${this._color}`;
}
}
// `add` factory method is defined on `Note`, but accessible
// on ColorNote subclass
let colorNote = ColorNote.add('My note', 'benmvp', '#0000ff');
// output: ID: note0
// Content: My Note
// Owner: benmvp
// Color: #0000ff
console.log(`${colorNote}`);
// output: true
console.log(Note.get('note0') === colorNote);
This is just a quick example of how ES6 classes work. Be sure to clone the Learning ES6 Github repo and take a look at the classes code examples page showing off the features in greater detail.
The example also uses default parameters, rest parameters, and the spread operator so you may want to revisit the relevant articles if you’re not familiar. It also makes use of template strings for string interpolation, so you should read up on that as well.
Continue reading “Learning ES6: Classes”