-
Notifications
You must be signed in to change notification settings - Fork 631
/
object.js
85 lines (67 loc) · 1.62 KB
/
object.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
'use strict';
// A simple class system, more documentation to come
const EventEmitter = require('events');
const lib = require('./lib');
function parentWrap(parent, prop) {
if (typeof parent !== 'function' || typeof prop !== 'function') {
return prop;
}
return function wrap() {
// Save the current parent method
const tmp = this.parent;
// Set parent to the previous method, call, and restore
this.parent = parent;
const res = prop.apply(this, arguments);
this.parent = tmp;
return res;
};
}
function extendClass(cls, name, props) {
props = props || {};
lib.keys(props).forEach(k => {
props[k] = parentWrap(cls.prototype[k], props[k]);
});
class subclass extends cls {
get typename() {
return name;
}
}
lib._assign(subclass.prototype, props);
return subclass;
}
class Obj {
constructor(...args) {
// Unfortunately necessary for backwards compatibility
this.init(...args);
}
init() {}
get typename() {
return this.constructor.name;
}
static extend(name, props) {
if (typeof name === 'object') {
props = name;
name = 'anonymous';
}
return extendClass(this, name, props);
}
}
class EmitterObj extends EventEmitter {
constructor(...args) {
super();
// Unfortunately necessary for backwards compatibility
this.init(...args);
}
init() {}
get typename() {
return this.constructor.name;
}
static extend(name, props) {
if (typeof name === 'object') {
props = name;
name = 'anonymous';
}
return extendClass(this, name, props);
}
}
module.exports = { Obj, EmitterObj };