-
Notifications
You must be signed in to change notification settings - Fork 0
/
din.js
120 lines (100 loc) · 3.52 KB
/
din.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
* Din - A JavaScript Double Inheritance Framework
* by Kambfhase
* v0.1.4
* MIT License
*/
var Class = (function (Object) {
"use strict";
function isFunction(fn) {
return typeof fn == "function";
}
function iterateOwnProperties(obj, callback, thisArg) {
// iterates over an objects own keys. skips weird properties on functions
var names = Object.getOwnPropertyNames(obj),
i = names.length,
name, isFn = isFunction(obj),
skip = iterateOwnProperties.skip;
while (i--) {
name = names[i];
if (!(isFn && ~skip.indexOf(name))) {
callback.call(thisArg, obj[name], name, obj);
}
}
}
iterateOwnProperties.skip = Object.getOwnPropertyNames(function () {}).concat(["prototype"]);
var objClass = {
create: function (obj) {
var klass = function self() {
return self.create.apply(self, arguments);
},
par = obj["parent"],
stat = obj["static"],
inst = obj["instance"];
if (par) {
iterateOwnProperties(par, function (prop, name) {
Object.defineProperty(klass, name, Object.getOwnPropertyDescriptor(par, name));
});
}
if (stat) {
Object.defineProperties(klass, stat);
}
klass.prototype = Object.create((par && par.prototype || Object.prototype), inst);
Object.defineProperty(klass.prototype, "constructor", {
value: klass,
enumerable: false,
configurable: true,
writable: true
});
if (!klass.create) {
klass.create = function () {
return Object.create(this.prototype);
};
}
if (!klass.is) {
klass.is = function (obj) {
return this.prototype.isPrototypeOf(obj);
};
}
return klass;
},
toPropertyDescriptorMap : function (obj) {
// takes a regular object as param and returns its property descriptor map.
var desc = {};
iterateOwnProperties(obj, function (prop, name) {
desc[name] = Object.getOwnPropertyDescriptor(obj, name);
});
return desc;
},
addSuper : function (obj, keyword) {
// adds a super property to all methods.
var par = obj["parent"],
stat = obj["static"],
inst = obj["instance"];
keyword = keyword || "super";
if (!par) {
return obj; // quick exit
}
if (stat) {
iterateOwnProperties(stat, function (prop, name) {
var value = prop.value;
if (value && isFunction(value)) {
value[keyword] = par[name];
}
});
}
if (inst) {
iterateOwnProperties(inst, function (prop, name) {
var value = prop.value;
if (value && isFunction(value)) {
value[keyword] = par.prototype[name];
}
});
}
return obj;
}
};
return objClass.create({
"static": objClass.toPropertyDescriptorMap(objClass)
});
})(Object);