How to define classes in Javascript

Strictly speaking, there’s no class in Javascript. To create objects of class, there are a few options:

1. Directly define an object as well as its vars/methods.  You cant create its instances in this case.

var foo = {
 x: [1,2,3],
 y: function(name) {
   return 'hello '+name;
 }
}

console.log(foo.x); //OK
console.log(foo.y('john')); //OK

var foo2 = new foo();//wrong: object is not a function

operator new has to be used on a function.

2. Define a function as well as its vars/methods. Create instance through new. For the vars there are two options:
2.1 vars are public members through “this.”.

var foo = function(name) {
  this.x = [1,2,3];
  this.y = function() {
    return 'hello '+name;
  }
}

console.log(foo.x);//undefined
console.log(foo.y());//no such method

var foo2 = new foo('john');

console.log(foo2.x);
console.log(foo2.y());

2.2 vars are private by not using this

var foo = function(name) {
  var x = [1,2,3];
  this.y = function() {
    return 'hello '+name;
  }
  this.getX = function() {
    return x;
  }
}

//console.log(foo.x);//undefined
//console.log(foo.y());//no such method

var foo2 = new foo('john');

console.log(foo2.x);//undefined. x becomes private
console.log(foo2.y());
console.log(foo2.getX());

3. Define a function. Vars/methods are added through prototype.. Create instance through new. This way instances all share the same method space improve runtime efficiency.

One thought on “How to define classes in Javascript

Leave a comment