What is the modern way to structure a "class" in JavaScript?

javascript

Solution

The modern way is to use `class`, as introduced in ES6.

class Movie {
    constructor(name) {
        this.name = name;
        // The "_" prefix is commonly used to denote "private" members.
        this._id = +new Date();
    }

    getName() {
        return `${this.name} ${this._id}`;
    }

    setName(name) {
        this.name = name;
    }
}

const movie = new Movie('Beerfest');

console.log(movie.getName());

The above example provides an equivalent interface to the original examples from 2010.

Original answer from 2010:

In "modern" JavaScript, there are three popular methods for defining objects.

The first method is the classic method and is still popular because of its simplicity; however, it is discouraged by MDC in favor of the second method because of the inefficiency of having to redefine each function every time an instance of the object is created.

// Constructor, methods and members all rolled up into one definition
var Movie = function(name) {
    this.name = name;
    // Note that private members can be created using the closure property
    var _id = +(new Date());

    this.getName = function() {
        return this.name + " " + _id;
    };

    this.setName = function(name) {
        this.name = name;
    };
};

var m = new Movie("Beerfest");

The second method is a variation of and can be used interchangeably with the first. It is also useful for adding new methods to existing objects via the `prototype` property. Private members and methods are not possible in this form.

// Constructor is separate from its methods
var Movie = function(name) {
    this.name = name;
}

Movie.prototype.getName = function() {
    return name;
};

Movie.prototype.setName = function(name) {
    this.name = name;
};

var m = new Movie("Kill Bill");

The third method is to use the module pattern, which makes it possible to instantiate objects without having to use the `new` operator.

var Movie = function (name) {
    var _id = +(new Date());
    var privateMethod = function() { alert(_id); };

    // All methods and members defined here are public
    return {
        name: name,
        getName: function() {
            return this.name + " " + _id;
        },
        setName: function(name) {
            this.name = name;
        }
    };
};

var m = Movie("Stackoverflow: the movie");

Note that in the first and third methods, you can use private access members and methods. But be aware that to use `this` within private methods some must happen.

Problem

How to build a "class" (with properties and methods) upon which will be created a lot of instances?

Original source