Skip to content

Instantly share code, notes, and snippets.

@lifeicd
Created November 26, 2011 05:33
Show Gist options
  • Select an option

  • Save lifeicd/1395098 to your computer and use it in GitHub Desktop.

Select an option

Save lifeicd/1395098 to your computer and use it in GitHub Desktop.
Class Lib
var Class = function(parent){
var klass = function(){
this.init.apply(this, arguments);
};
// Change klass' prototype
if (parent) {
var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
};
klass.prototype.init = function(){};
klass.fn = klass.prototype;
// Adding a proxy function
klass.proxy = function(func){
var self = this;
return(function(){
return func.apply(self, arguments);
});
}
// extend: static method
klass.extend = function(obj){
var extended = obj.extended;
for(var i in obj){
klass[i] = obj[i];
}
if (extended) extended(klass)
}
// include: instance method
klass.include = function(obj){
// ...
for(var i in obj){
klass.prototype[i] = obj[i]
}
///...
}
// Add the function on instances too
klass.fn.proxy = klass.proxy;
return klass;
};
// inheritance
var Animal = new Class;
Animal.include({
breath: function() {
console.log('whew!');
}
});
var Cat = new Animal;
var tom = new Cat;
tom instanceof Cat // true
tom instanceof Animal // true
tom.breath();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment