Created
December 6, 2012 15:35
-
-
Save gitawego/4225383 to your computer and use it in GitHub Desktop.
a simple method for class declaration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function declare(Parent, props) { | |
"use strict"; | |
var Factory, Super, i | |
, __construct = props.__construct || function () { | |
} | |
, toArr = function (args) { | |
var a = []; | |
for (var i = 0, l = args.length; i < l; i++) { | |
a[i] = args[i]; | |
} | |
return a; | |
}; | |
delete props.__construct; | |
//new constructor | |
Factory = function () { | |
if (Factory.prototype.hasOwnProperty("__construct")) { | |
Factory.prototype.__construct.apply(this, arguments); | |
} | |
}; | |
//inherit | |
Parent = Parent || Object; | |
Super = function () { | |
}; | |
Super.prototype = Parent.prototype; | |
Factory.prototype = new Super(); | |
Factory.superClass = Parent.prototype; | |
Factory.prototype.constructor = Factory; | |
Factory.prototype.super = function (name,args) { | |
if (!name) { | |
throw new Error("method name must be defined"); | |
} | |
//args = toArr(arguments); | |
if (Factory.superClass && Factory.superClass.hasOwnProperty(name)) { | |
return Factory.superClass[name].apply(this, args); | |
} | |
}; | |
Factory.prototype.__construct = function () { | |
if (Factory.superClass && Factory.superClass.hasOwnProperty("__construct")) { | |
Factory.superClass.__construct.apply(this, arguments); | |
} | |
__construct.apply(this, arguments); | |
}; | |
// add implementation methods | |
for (i in props) { | |
if (props.hasOwnProperty(i)) { | |
Factory.prototype[i] = props[i]; | |
} | |
} | |
// return the "class" | |
return Factory; | |
} | |
//test | |
var A = declare(null, { | |
__construct: function () { | |
console.log("called constructor A"); | |
}, | |
a: 1, | |
c:function(){ | |
console.log("c of A"); | |
} | |
}); | |
var B = declare(A, { | |
__construct: function () { | |
console.log("called constructor B"); | |
}, | |
b: 2, | |
c:function(){ | |
this.super('c',arguments); | |
console.log("c of B"); | |
} | |
}); | |
var x = new B(); | |
x.c(); | |
console.log(x instanceof A); | |
console.log(x instanceof B); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment