Created
March 10, 2012 06:33
-
-
Save laughinghan/2010599 to your computer and use it in GitHub Desktop.
Python-style classes in JavaScript
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
//because why not? | |
//please don't actually use this. Please use idiomatic JavaScript classes or a very thin class layer like github.com/jayferd/pjs | |
/* | |
Usage: | |
var Cat = PyClass({ | |
__init__: function(self, name) { | |
self.name = name; | |
}, | |
chase: function(self, prey) { | |
console.log(self.name + ' is chasing ' + prey); | |
} | |
}); | |
var HouseCat = PyClass(Cat, { | |
chase: function(self) { | |
Cat.chase(self, 'yarn'); | |
} | |
}); | |
var kitty = HouseCat('Kitty'); | |
kitty.chase(); | |
*/ | |
function PyClass(sup, defs) { | |
if (arguments.length === 1) { | |
defs = sup; | |
sup = PyClass.Object; | |
} | |
function cons() { | |
if (this instanceof cons) return; | |
var self = new cons; | |
self.__init__.apply(self, arguments); | |
return self; | |
} | |
var proto = cons.prototype = PyClass.Object(sup.prototype); | |
for (var methodName in defs) (function(methodName, method) { | |
cons[methodName] = method; | |
proto[methodName] = function() { | |
method.apply(null, [].concat.apply([this], arguments)); | |
}; | |
}(methodName, defs[methodName])); | |
return cons; | |
} | |
PyClass.Object = function(proto) { | |
if (proto) { | |
var cons = function(){}; | |
cons.prototype = proto; | |
return new cons; | |
} | |
}; | |
PyClass.Object.prototype.__init__ = function(){}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment