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.
Created
March 25, 2014 15:33
-
-
Save mbriggs/9764321 to your computer and use it in GitHub Desktop.
Simple class abstraction in js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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