Skip to content

Instantly share code, notes, and snippets.

@mbriggs mbriggs/README.md
Created Mar 25, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.