cor-lang
Version:
The Language of the Web
99 lines (76 loc) • 1.72 kB
JavaScript
(function(cor){
/*
A library to provide some OO features across
Cor source code
Usage:
var
Class = cor.Class;
var A = Class({
init: function(){
this.xx = true;
this.y()
},
y: function(){
console.log('A')
}
})
var B = Class(A, {
y: function(){
this.base('y')
console.log('B')
}
})
var C = Class(B, {
y: function(){
this.base('y')
console.log('C')
}
})
c = new C()
c;
*/
var
hasProp = Object.prototype.hasOwnProperty;
function Class(Base, classBody){
if (! classBody){
classBody = Base || {};
Base = function(){};
}
var
key, member,
base = newBaseMethod(),
Class = newClass(),
proto = Object.create(Base.prototype);
for (key in classBody) {
if (! hasProp.call(classBody, key)){
continue;
}
member = classBody[key];
if (typeof member === 'function') {
member.$owner = Class;
}
proto[key] = classBody[key];
}
proto._base_ = Base;
proto.base = base;
Class.prototype = proto;
return Class;
};
function newClass() {
return function() {
(typeof this.init === 'function') && this.init.apply(this, arguments);
};
}
function newBaseMethod() {
return function base(methodName, args){
var
callerMethod = this.base.caller,
meth = callerMethod.$owner.prototype._base_.prototype[methodName];
if (typeof meth === 'function') {
return meth.apply(this, args);
}
throw "Can not find the base method '" + methodName + "'";
};
}
cor.Class = Class;
})(typeof cor === 'undefined' ? {} : cor);