Classes in Javascript

Instance properties, instance methods, class properties, class methods: yes, you can have all of these in Javascript, but you need to remember when to use ‘var’, when to use ‘this’ and when to use ‘that’.

Since I don’t seem to be able to easily remember all this stuff I wrote a small code sample that uses all of them. To run it, open the Javascript console in Chrome (CTRL-SHIFT-J on Windows) and run this baby:


function MyConstructor() {
  var that = this;
  this.publicInstanceProperty = "publicInstanceProperty";
  var privateInstanceProperty = "privateInstanceProperty";
  var privateInstanceMethod = function() {
    console.assert(that.publicInstanceProperty === "publicInstanceProperty");
    console.assert(privateInstanceProperty === "privateInstanceProperty");
  }
  privateInstanceMethod();
  // A privileged method is able to access the private variables and methods
  // it is itself accessible to the public methods and the outside.
  this.privilegedInstanceMethod = function() {
    console.assert(that.publicInstanceProperty === "publicInstanceProperty");
    console.assert(privateInstanceProperty === "privateInstanceProperty");
  }
};
MyConstructor.prototype.publicInstanceMethod = function() {
  console.assert(this.publicInstanceProperty === "publicInstanceProperty");
  console.assert(this.privateInstanceProperty === undefined);
  // this.privateInstanceMethod(); // TypeError: Object #<MyConstructor> has no method 'privateInstanceMethod'
};
MyConstructor.classProperty = "classProperty";
MyConstructor.classMethod = function() { };

//////////
// main //
//////////
var ctx = new MyConstructor();
console.assert(ctx.publicInstanceProperty === "publicInstanceProperty");
console.assert(ctx.privateInstanceProperty === undefined);
ctx.publicInstanceMethod();
// ctx.privateInstanceMethod(); // TypeError: Object #<MyConstructor> has no method 'privateInstanceMethod'
ctx.privilegedInstanceMethod();
console.assert(MyConstructor.classProperty === "classProperty");
MyConstructor.classMethod();

Douglas Crockford was the first to write about creating private instance properties/methods in Javascript. Each time you see the “var that = this” trick, that’s him !

However, I find this stackoverflow post to be easier to understand.