6

I heard that some sort of class system will be added to JavaScript with ECMAScript and I find that a little confusing, because I've just finished reading a JS book, JavaScript, The Good Parts by Douglas Crockford, where he explained that the lack of classes wasn't a bad thing at all, it was just different. I believe I've seen it explained that any similarity to a class-based language was just to lessen confusion during that era or something like that, to help JS catch on.

From my understanding, JavaScript isn't supposed to have classes, they just aren't part of JS's design. Does ES6 fundamentally change JS functionality or is it just syntax sugar?

15

The ES6 class syntax does not change the functionality of Javascript at all. It is merely syntax sugar for prototype declarations. Once parsed, it just creates prototype objects which can then be used in an OO fashion the same way manually declared prototype objects have always been used in JS. So, the class syntax doesn't really change anything except make prototype definitions prettier to declare. The resulting objects are no more class-like than what people did manually in ES5.

Here's an example (run only in a browser that supports the ES6 class syntax like Chrome as of Dec 2015).

// ES6 class syntax
class Polygon {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    calcArea() {
        return this.height * this.width;
    }
    get area() {
        return this.calcArea()
    }
}

// ES5 equivalent prototype syntax
function Poly(height, width) {
    this.height = height;
    this.width = width;
}

Object.defineProperties(Poly.prototype, {
    calcArea: {
        value: function () {
            return this.height * this.width;
        }
    },
    area: {
        get: function () {
            return this.calcArea();
        }
    }
});

var p1 = new Polygon(10, 20);
var p2 = new Poly(10, 20);
log(p1.area);
log(p2.area);
log(Object.getOwnPropertyNames(Object.getPrototypeOf(p1)));
log(Object.getOwnPropertyNames(Object.getPrototypeOf(p2)));

Output in Chrome as of Dec 2015:

200
200
["constructor","calcArea","area"]
["constructor","calcArea","area"]

Working jsFiddle: http://jsfiddle.net/jfriend00/92hhohdc/

  • Good answer which I upvoted, but I would prefer an example, if it can be simple and short – Basile Starynkevitch Dec 7 '15 at 13:57
  • @BasileStarynkevitch - Code example added. – jfriend00 Dec 9 '15 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.