JavaScript Gets Classy!

If you are a Web Development professional, and you haven’t been living under a rock, you’ll know that some pretty excited stuff is coming our way with ECMAScript 6. One of the most exciting additions is classes. This will eliminate the need to use syntactic sugar to create class-like structures from functions.

The use of classes as a means of encapsulating groups of functionality into a cohesive object with an easy to understand public interface is a basic tenant of OOP. Because this concept is so powerful, and because most professionals who use JavaScript also use languages which have an OOP capable structure, we tend to try to replicate this structure in JavaScript.

Let’s get technical for just a minute about what this really means for JavaScript. JavaScript is a language that uses object prototypes for inheritance whereas most languages use classes. With this seemingly basic change, the way we use JavaScript will change radically (for the good IMO).

ECMAScript 5 “Class”

var AnchorMan = function(name) {
    this.name = name;
};

AnchorMan.prototype.closing_line = function() {
    return 'I\'m '+this.name+', you stay classy San Diego!';
};

var RonBurgundy = new AnchorMan('Ron Burgundy');

console.log(RonBurgundy.closing_line()); 
// --> logs 'I\'m Ron Burgundy, you stay classy San Diego!'

By augmenting the AnchorMan object with a closing_line function we have added property that our constructed ‘Class’ will inherit. This syntax is a little confusing to a developer who uses true class structures, and that’s why ECMAScript 6 is introducing the classical declarative syntax for classes.

ECMAScript 6 Class

class AnchorMan {
    constructor(name) {
        this.name = name;
    }
    
    closing_line() {
        return 'I\'m '+this.name+', you stay classy San Diego!';
    }
}

var RonBurgundy = new AnchorMan('Ron Burgundy');

console.log(RonBurgundy.closing_line());
// --> logs 'I\'m Ron Burgundy, you stay classy San Diego!'

This doesn’t seem like such a huge change on the surface, but you can imagine that with the ability to augment our AnchorMan object on the fly by changing the prototype, things could get out of hand!

My one major qualm with the ES6 spec is that there are still no private properties! When the spec was first drafted there was a notion that you could use the Symbol object to create private properties, but that is no longer the case. So I pose this question; without too much syntactic sugar, how do we keep properties private?

Stay classy San Diego!