Skip to content

Instantly share code, notes, and snippets.

@sfaleron
Created February 27, 2017 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfaleron/6ad5c8c522aa33634c463fa9675f994f to your computer and use it in GitHub Desktop.
Save sfaleron/6ad5c8c522aa33634c463fa9675f994f to your computer and use it in GitHub Desktop.
Making JS classier. Until moving on to something with classiness baked-in that compiles to JS :)
// Requires ES5
// Inheritance pattern inspired by http://stackoverflow.com/a/5546053
// instanceOf has the usual straightforward-inheritance-checker problems with iFrames
if (typeof classyJS === 'undefined') {
var classyJS = (function () {
'use strict';
var my = Object.create(null);
my.NullObj = function () { return Object.create(null); };
my.$super = function (cls) { return cls._parent; };
my.instanceOf = function (inst, cls) {
if (typeof cls.prototype === 'undefined') return false;
else return Object.isPrototypeOf.call(cls.prototype, inst);
};
var extend = function (cls) {
var subcls = my.NullObj();
subcls.prototype = Object.create(cls.prototype);
subcls.create = function () {
var inst = Object.create(subcls.prototype);
if (inst.init instanceof Function) inst.init.apply(inst, arguments);
return inst;
};
subcls.extend = function () { return extend(subcls); };
subcls._parent = cls;
return subcls;
};
my.BaseObj = (function () {
var cls = my.NullObj();
cls._parent = null;
cls.prototype = my.NullObj();
cls.prototype.instanceOf = function (kls) {
return my.instanceOf(this, kls);
};
cls.extend = function() { return extend(cls); };
cls.create = function() { return Object.create(cls.prototype); };
return cls;
}());
return my;
}());
}
else alert('Namespace collision while loading classyJS library.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment