Skip to content

Instantly share code, notes, and snippets.

@jedrichards
Created May 16, 2013 10:36
Show Gist options
  • Save jedrichards/5590832 to your computer and use it in GitHub Desktop.
Save jedrichards/5590832 to your computer and use it in GitHub Desktop.

Revisions

  1. Jed Richards created this gist May 16, 2013.
    59 changes: 59 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    // extend.js
    define(function (require) {

    var _ = require("vendor/underscore");

    var ctor = function () {};

    var inherits = function (parent,protoProps,staticProps) {
    var child;
    if (protoProps && protoProps.hasOwnProperty("constructor")) {
    child = protoProps.constructor;
    } else {
    child = function () { return parent.apply(this,arguments); };
    }
    _.extend(child,parent);
    ctor.prototype = parent.prototype;
    child.prototype = new ctor();
    if (protoProps) _.extend(child.prototype,protoProps);
    if (staticProps) _.extend(child,staticProps);
    child.prototype.constructor = child;
    child.__super__ = parent.prototype;
    return child;
    };

    function extendThis (protoProps,staticProps) {
    var child = inherits(this,protoProps,staticProps);
    child.extend = extendThis;
    return child;
    }

    return extendThis.bind(extendThis);
    });

    // Usage

    define(function (require) {

    var extend = require("extend");

    var MyClass = extend({
    init: function (options) {
    console.log("MyClass.init");
    }
    });

    var myClass = new MyClass();
    myClass.init({}); // MyClass.init

    var MySubClass = MyClass.extend({
    init: function (options) {
    MyClass.prototype.init.call(this,options);
    console.log("MySubClass.init");
    }
    });

    var mySubClass = new MySubClass();
    mySubClass.init(); // MyClass.init + MySubClass.init

    });