Hemanth's Scribes

javascript

Classes in JavaScript ES6

Author Photo

Hemanth HM

Thumbnail

Well, well… there are so many JavaScript frameworks that already try to implement classes as per the classical Object Oriented Class definition.

But, with Harmony (ES6) implementing classes like classical OO shall be possible.

This might be something like the IPv6 boom, most of the JavaScript hackers are used to making use of first class functions as classes and that shall remain along with this paradigm, is what I feel personally.

Let’s see few of the famous frameworks, that make use of classes:

// Mootools
var Monkey = new Class({
    initialize: function(name) {
        this.name = name;
    }
});

// Prototype
var Monkey = Class.create({
  initialize: function(name) {
    this.name = name;
  }
});

// YUI
var Monkey = Y.Base.create('monkey', null, [], {
  initializer: function(name) {
    this.name = name;
  }
});

// dojo
var Monkey = declare(null, {
  constructor: function(name) {
    this.name = name;
  }
});

But now with ES6 (Harmony):

// From the proposal
class Monster {
  // The contextual keyword "constructor" followed by an argument
  // list and a body defines the body of the class's constructor
  // function. public and private declarations in the constructor
  // declare and initialize per-instance properties.
  constructor(name, health) {
    public name = name;
    private health = health;
  }

  // An identifier followed by an argument list and body defines a
  // method. A "method" here is simply a function property on some
  // object.
  attack(target) {
    log('The monster attacks ' + target);
  }

  // The contextual keyword "get" followed by an identifier and
  // a curly body defines a getter
  get isAlive() {
    return private(this).health > 0;
  }

  // Likewise, "set" can be used to define setters.
  set health(value) {
    if (value < 0) {
      throw new Error('Health must be non-negative.');
    }
    private(this).health = value;
  }
}

Grammar:

ClassElement :
    Constructor
    PrototypePropertyDefinition
    ClassPropertyDefinition

Constructor :
    constructor ( FormalParameterList? ) { ConstructorBody }

ConstructorBody :
    ConstructorElement*

ConstructorElement :
    Statement                   // but not ReturnStatement
    Declaration
    InstancePropertyDefinition

PrototypePropertyDefinition :
    public ExportableDefinition
    Identifier     ( FormalParameterList? ) { FunctionBody } // method
    get Identifier ( )                      { FunctionBody } // getter
    set Identifier ( FormalParameter )      { FunctionBody } // setter

ClassPropertyDefinition :
    static ExportableDefinition

InstancePropertyDefinition :
    public ExportableDefinition

ExportableDefinition :
    Declaration
    VariableDeclarationList ;                                // data properties
    Identifier     ( FormalParameterList? ) { FunctionBody } // method
    get Identifier ( )                      { FunctionBody } // getter
    set Identifier ( FormalParameter )      { FunctionBody } // setter
    MemberAdjective ExportableDefinition

Inheritance in JavaScript:

class Base {}
class Derived extends Base {}

// Here, Derived.prototype will inherit from Base.prototype.

let parent = {};
class Derived prototype parent {}

Classical Object Oriented Class with JavaScript is still debatable, but with this paradigm a clear line shall be drawn between Classes and Functions. JavaScript isn’t a pure functional language. In fact it’s rather multi-paradigm but How useful this will be? Is it needed?

Do read about Harmonious Classes.

Let me try to demonstrate how it might or might not be useful:

So far JavaScript hackers are used to implementing classes as:

  • Using a function.
  • Internal methods and prototype based inheritances.
  • Using object literals

But now, with this syntax in place it might be useful to draw clear lines between classes and functions.

On the other hand, with functions emulating whatever classical OO classes do, we might as well code and understand the code easily.

Update 0:

Tentative addition of Class Definitions Syntax and Semantics in 13.5 based upon Maximally Minimal Strawman. NOTE-Classes do not yet have full consensus within TC39 and may not survive.

#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.