Skip to content

Instantly share code, notes, and snippets.

@zgangx
Last active September 16, 2020 21:24
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 zgangx/5e2f1da45ac852619fd9d92d89da0dfb to your computer and use it in GitHub Desktop.
Save zgangx/5e2f1da45ac852619fd9d92d89da0dfb to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/miviziy
//class emulation adding inheritance
var Class = function(parent){
var klass = function(){
this.init.apply(this, arguments);
};
// Change klass' prototype
//If a parent is passed to the Class constructor
//we make sure any subclasses share the same prototype.
//creating a temporary anonymous function prevents instances
//from being created when a class is inherited.
//here is that only instance properties, not class properties, are inherited
if (parent) {
var subclass = function() {};
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
};
klass.prototype.init = function(){};
// Shortcut to access prototype
klass.fn = klass.prototype;
// Adding a proxy function
klass.proxy = function(func){
var self = this;
return(function(){
return func.apply(self, arguments);
});
}
// Add the function on instances too
klass.fn.proxy = klass.proxy;
// Shortcut to access class
klass.fn.parent = klass;
klass._super = klass.__proto__;
// Adding class properties
klass.extend = function(obj){
var extended = obj.extended;
for(var i in obj){
klass[i] = obj[i];
}
if (extended) extended(klass)
};
// Adding instance properties
klass.include = function(obj){
var included = obj.included;
for(var i in obj){
klass.fn[i] = obj[i];
}
if (included) included(klass)
};
return klass;
};
//usage
var Animal = new Class;
Animal.include({
breath: function(){
console.log('breath')
}
});
var Cat = new Class(Animal);
var tommy = new Cat;
tommy.breath();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment