Working on a simple JavaScript idea with implementing Interfaces. Some thought, I have come with this idea. I haven’t worked with it.
For better readability, I extended the Function class:
1: //Enforces similar data types and has been overridden
2: Function.prototype.interface = function () {
3: if (arguments.length < 1) {
4: throw new Error("Interface constructor called with no arguments.");
5: }
6: var dv = (document.defaultView) ? document.defaultView : document.parentWindow; //Covers < IE9
7:
8: for (var i = 0,length = arguments.length; i < length; i++) {
9: var v = (dv[arguments[i]])
10: ? new dv[arguments[i]]
11: : {};
12: for (var j in v) {
13: if (this.hasOwnProperty(j)) {
14: continue;
15: }
16:
17: //Set to generic function enforcing similar types.
18: this.prototype[j] = (function(item) {
19: return function (value, overridden) {
20: if (!(overridden && overridden.OR)) {
21: throw new Error("Must be overridden.")
22: }
23: if (Object.prototype.toString.call(value) !== Object.prototype.toString.call(item)) {
24: throw new Error("Members are different types.")
25: };
26: return value;
27:
28: }}(v[j]));
29: }
30: }
31:
32: return this;
33: };
34: Function.prototype.override = function (value) {
35: return this.call(null, value,{OR:true});
36: };
1: var Class1 = function Class1() {
2: this.add = {};
3: this.subtract = [];
4: };
5:
6: var Class2 = function () {
7: this.times = function () { };
8: this.multiply = 9;
9: };
1: var Class3 = function () {
2: this.car = "blue";
3: }.interface("Class1").interface("Class2");
The Composite could also be written:
1: var Class3 = function () {
2: this.car = "blue";
3: }.interface("Class1","Class2");
1: var c = new Class3();
1: c.add = c.add.override({ Kirk: "Time" });
1: c.add = c.add({ Kirk: "Time" }); //Error is thrown
This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”
Henry Ford
No comments:
Post a Comment