-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclassical.js
98 lines (79 loc) · 2.39 KB
/
classical.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
/*eslint no-eval:0 */
'use strict';
var _ = require('underscore');
var util = require('util');
function defaultInitialize(options) {
_.extend(this, options);
}
var Classical = function(options) {
Classical.validateOptions(options);
this.name = options.name || 'DefaultClass';
this.inherits = options.inherits || [];
this.initialize = options.initialize || defaultInitialize;
this.classMethods = options.classMethods || {};
this.instanceMethods = options.instanceMethods || {};
};
// Class Methods.
_.extend(Classical, {
toString: function() {
return util.inspect(this);
},
validateOptions: function(options) {
var self = this;
_.each(options, function(value, key) {
var desiredType = self.validOptions[key];
if (!desiredType) {
throw new Error('Option ' + key + ' not in ' + _.keys(self.validOptions).join(','));
}
if (typeof value !== desiredType) {
throw new Error('Option ' + key + ' expected ' + desiredType);
}
});
},
validOptions: {
name: 'string',
inherits: 'object',
initialize: 'function',
classMethods: 'object',
instanceMethods: 'object'
},
makeInitializer: function(classInstance) {
var initializer = function(options) {
var self = this;
_.each(classInstance.inherits, function(ancestor) {
ancestor.call(self, options);
});
classInstance.initialize.call(self, options);
};
return initializer;
}
});
// Instance Methods
_.extend(Classical.prototype, {
createClass: function() {
var initializer = Classical.makeInitializer(this);
var Class = this.makeConstructor(this.name, initializer);
this.addClassMethods(Class);
this.addInstanceMethods(Class);
return Class;
},
makeConstructor: function(name, body) {
var constructor = eval(
'function ' + name + '(options) { body.call(this, options); } ' + name
);
constructor.toString = Classical.toString;
return constructor;
},
addClassMethods: function(Class) {
var extensions = this.inherits.concat([this.classMethods]);
_.extend.apply(null, [Class].concat(extensions));
},
addInstanceMethods: function(Class) {
var extensions = _.map(this.inherits, function(ancestor) {
return ancestor.prototype;
})
.concat([this.instanceMethods]);
_.extend.apply(null, [Class.prototype].concat(extensions));
}
});
module.exports = Classical;