Created
June 10, 2015 04:41
-
-
Save leviwheatcroft/ea19af03478845982a3d to your computer and use it in GitHub Desktop.
js class & factory functions: vanilla, minimal, and flexible
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
(function() { | |
var createClass; | |
var createFactory; | |
var Factory; | |
createClass = function(pattern) { | |
var Cls; | |
var Tmp; | |
var proto; | |
Cls = function() { | |
this.init.apply(this, arguments); | |
}; | |
if (pattern.hasOwnProperty('parent')) { | |
//avoid calling parent constructor | |
Tmp = function() {}; | |
Tmp.prototype = pattern.parent.prototype; | |
Tmp.prototype.initSuper = pattern.parent.prototype.init; | |
proto = new Tmp(); | |
} else { | |
proto = {}; | |
} | |
Object.getOwnPropertyNames(pattern).forEach(function(val) { | |
proto[val] = pattern[val]; | |
}); | |
proto.constructor = Cls; | |
Cls.prototype = proto; | |
return Cls; | |
}, | |
createFactory = function(Cls) { | |
return new Factory(Cls); | |
}; | |
Factory = function(Cls) { | |
this.Cls = Cls; | |
this.instances = []; | |
}; | |
Factory.prototype = { | |
spawn: function() { | |
var factory; | |
var Cls; | |
var cls; | |
factory = this; | |
var Cls = function() {}; | |
Cls.prototype = this.Cls.prototype; | |
cls = new Cls(); | |
cls.init.apply(cls, arguments); | |
this.instances.push(cls); | |
return cls; | |
} | |
}; | |
_.mixin({ | |
createClass: createClass, | |
createFactory: createFactory | |
}); | |
})(); | |
var A = _.createClass({ | |
init: function() { | |
console.log('init A'); | |
}, | |
methodA: function() { | |
console.log('method A'); | |
} | |
}); | |
var B = _.createClass({ | |
parent: A, | |
init: function() { | |
this.initSuper(); | |
console.log('init B'); | |
}, | |
methodB: function() { | |
console.log('method B'); | |
} | |
}); | |
var factoryB = _(B).createFactory(); | |
b1 = factoryB.spawn(); | |
b2 = factoryB.spawn(); | |
b3 = factoryB.spawn(); | |
_(factoryB.instances).each(function(b) { | |
b.methodA(); | |
b.methodB(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment