Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple example of JavaScript namespaces, classes and inheritance

I've been asked to port some of our PHP code across to JavaScript, so that more of our logic runs client-side. What'd I'd like is a simple example that shows:

  • a namespace ("Package") containing two classes ("Master" and "Slave")
  • the "Master" class has a property "p", a function "m" and a constructor that takes a single argument to set the initial value of "p"
  • the "Slave" class inherits both "p", the constructor and "m" from the "Master" class

I don't mind using some sort of existing framework, but it must be lightweight -- ideally no more than 200 LOC (un-minified).

Here's my attempt, FWIW:

var Package = {};

Package.Master = function(pValue) {
    this.p = pValue;
    this.m = function() {
        alert("mmmmm");
    }
}

Package.Slave = function(pValue) {
    // this will inherit from Package.Master
}

// one of the many online examples:
// http://kevlindev.com/tutorials/javascript/inheritance/index.htm
KevLinDev.extend = function(subClass, baseClass) {
   function inheritance() {}
   inheritance.prototype = baseClass.prototype;

   subClass.prototype = new inheritance();
   subClass.prototype.constructor = subClass;
   subClass.baseConstructor = baseClass;
   subClass.superClass = baseClass.prototype;
}

KevLinDev.extend(Package.Slave, Package.Master);
like image 603
wpearse Avatar asked May 03 '11 20:05

wpearse


1 Answers

I'm quite a fan of John Resig's Simple Javascript Inheritance.

E.g.:

var Package = {};
Package.Master = Class.extend({
    init: function(pValue) {
        this.p = pValue;
    },
    m: function() {
        alert("mmmmm");
    }
});

Package.Slave = Package.Master.extend({
    init: function(pValue) {
        this._super(pValue);
    }
});

var slave = new Package.Slave(10);
slave.m();
like image 165
Matthew Abbott Avatar answered Nov 02 '22 07:11

Matthew Abbott