25 May 2015

Extendable "Classes" in javascript

Tags: javascript

This article will provide a simple method of creating (close to) inheritable classes in JavaScript.

Now since JavaScript is prototypal rather than classical, these are of course not real classes persee, but a way of replicating the functionality offered by other languages - in javascript.

javascript-example.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/ The constructor /
var Apple = function(options) {
  return new Apple.prototype.init(options);
};

Apple.prototype = {
  init: function(options) {
    / init function will get invoked when a new Apple is created /
  },

  Eat: function() {
    console.log('Apple eaten!');
  }
}

/ put the original constructor back /
Apple.prototype.init.prototype = Apple.prototype;