How to define a class in javascript

As JavaScript is an object oriented language (may be not really object oriented, see discussions here), you may want to define classes and instantiate object from these classes like you would in other strongly typed languages (e.g. Java). But javascript doesn’t support classes, a.k.a there ara no classes in javascript. Instead of defining classes, you may define objects via using function keyword like this:

function User(id,name) {
    this.id = id;
    this.name = name;
    this.password = undefined;
}

And then you can instantiate it with new keyword:

var user = new User(1, "Max");

In javascript all objects may be extended on the fly (unless they are frozen). For example you may add new property or method into user object defined above.

user.age = 17;
user.isFullAged = function (){
    if (this.age >= 18){
        return true;
    } else {
        return false;
    }
}

If you want a method or property defined in all instances of an object you may add above extension directly into the object definition:

function User(id,name) {
    this.id = id;
    this.name = name;
    this.password = undefined;
    this.age = 0;
    this.isFullAged = function (){
        if (this.age >= 18){
            return true;
        } else {
            return false;
        };
}

The drawback of above technic is everytime if you create a new instance of user object, the function isFullAged created again and this means wasting resources. To avoid that, you may define object method once and inherit it from object definition for each instance. For this javascript provide a different mechanism called prototype (see more details about prototype and inheritance here).

User.prototype.toString = function(){
    return "UserId: " + this.id + " / Username: " + this.name;
};

Now every instance of User objects has a method called toString with the functionality defined above and this time the method toString created only once.