Skip to content

Instantly share code, notes, and snippets.

@mbriggs
Created March 25, 2014 15:33
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 mbriggs/9764321 to your computer and use it in GitHub Desktop.
Save mbriggs/9764321 to your computer and use it in GitHub Desktop.
Simple class abstraction in js

Simple js class abstraction

Basically it is backbones self-propegating extend method, slightly hacked up to allow the definition of __name__. Defining this means that you will never end up seeing child when looking at your class in the dev tools. Also adds a define method for creating singletons.

var extend = function(protoProps, staticProps){
var parent = this;
var child;
var nameProp = ((staticProps && staticProps.nameProp) || this.nameProp);
if (protoProps) {
var name = (protoProps[nameProp] || this[nameProp]);
var constructor = protoProps.hasOwnProperty('constructor') ? protoProps.constructor : this;
protoProps = _.extend(protoProps, { constructor: namedConstructor(name, constructor) });
}
if(protoProps && _.has(protoProps, 'constructor')){
child = protoProps.constructor;
} else{
child = function(){
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
var Surrogate = function(){
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if(protoProps) _.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
};
var Class = function(){ this.initialize.apply(this, arguments) };
Class.nameProp = '__name__';
Class.__name__ = 'Class';
Class.prototype.initialize = function(){};
Class.extend = extend;
Class.define = function(definition){
var klass = this.extend(definition);
return new klass();
};
function namedConstructor(name, constructor) {
var fn = new Function('constructor', 'return function ' + name + '(){ '
+ 'constructor.apply(this, arguments) '
+ '};');
return fn(constructor);
}
return Class;
var Singleton = Class.define({
foo: function(){
return "there can be only one!";
}
});
Singleton.foo(); //=> "there can be only one!"
var Foo = Class.extend({
__name__: 'Foo'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment