Skip to content

Instantly share code, notes, and snippets.

@laughinghan
Created March 10, 2012 06: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 laughinghan/2010599 to your computer and use it in GitHub Desktop.
Save laughinghan/2010599 to your computer and use it in GitHub Desktop.
Python-style classes in JavaScript
//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