Skip to content

Instantly share code, notes, and snippets.

@xulapp
Created March 12, 2010 14:08
Show Gist options
  • Select an option

  • Save xulapp/330339 to your computer and use it in GitHub Desktop.

Select an option

Save xulapp/330339 to your computer and use it in GitHub Desktop.
Class
function Class(sup, pro) {
if (sup && typeof sup === 'object')
pro = sup, sup = Object;
var con = Object.getOwnPropertyDescriptor(pro, 'constructor');
if (!con)
con = {value: Function(), writable: true, configurable: true};
if (con.configurable) {
con.enumerable = false;
Object.defineProperty(pro, 'constructor', con);
}
con = pro.constructor;
con.prototype = pro;
con.superclass = sup;
con.__proto__ = Class.prototype;
pro.__proto__ = sup && sup.prototype;
return Proxy.createFunction(con, function() con.createInstance(arguments));
}
Class = Class(Function, {
constructor: Class,
$super: function $super() {
var sup = this.superclass;
var method = sup.prototype[$super.caller === this ? 'constructor' : $super.caller.name];
return Function.prototype.call.apply(method, arguments);
},
isSubClass: function isSubClass(cls) {
return this.prototype instanceof cls;
},
createInstance: function createInstance(args) {
var instance = Object.create(this.prototype);
var result = this.apply(instance, args || []);
return result instanceof Object ? result : instance;
},
toString: function toString() {
var arr = [];
var cls = this;
do {
arr.push(cls.name);
} while (cls = cls.superclass);
return '[object Class [class ' + arr.join(', ') + ']]';
},
getOwnPropertyDescriptor: function(name) Object.getOwnPropertyDescriptor(this, name),
getPropertyDescriptor: function(name) Object.getPropertyDescriptor(this, name),
getOwnPropertyNames: function(name) Object.getOwnPropertyNames(this, name),
getPropertyNames: function(name) Object.getPropertyNames(this, name),
defineProperty: function(name) Object.defineProperty(this, name),
delete: function(name) delete this[name],
fix: function() {
if (!Object.isFrozen(this))
return void 0;
var res = {};
Object.getOwnPropertyNames(this).forEach(function(name) {
res[name] = Object.getOwnPropertyDescriptor(this, name);
}, this);
return res;
},
has: function(name) name in this,
hasOwn: function(name) Object.prototype.hasOwnProperty.call(this, name),
get: function(receiver, name) {
if (name in this)
return this[name];
var method = this.prototype[name];
if (typeof method === 'function')
return Function.prototype.call.bind(method);
return void 0;
},
set: function(receiver, name, val) this[name] = val,
enumerate: function() [name for (name in this)],
keys: function() Object.keys(this),
});
@xulapp
Copy link
Copy Markdown
Author

xulapp commented Jul 18, 2010

Here is my Greasemonkey script using this code.
http://userscripts.org/scripts/show/67840

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment