-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.js
51 lines (51 loc) · 2 KB
/
class.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
/**
* @function Class
* @constructor
*
* Class creator
*
* @param prototype {Object} The prototype object
*
* @returns {Function} constructor
**/
function Class( prototype ) {
prototype = prototype || {};
var parent = typeof prototype.Extends == 'function' ? prototype.Extends.prototype : {};
// create our constructor - use provided `initialize`
// method or create empty function
var constructor = function () {
var params = [].slice.call( arguments );
// get the constructor function
var fn = (prototype.initialize || parent.initialize || function () {});
// create empty function that we will use for the real constructor
var empty = function () {};
// link prototypes
empty.prototype = constructor.prototype;
// create the new instance; `instance` will inherit the `constructor` prototype
var instance = new empty();
// execute the constructor function, changing the context with the `instance`
var return_val = fn.apply( instance, params );
// In case the return result of the constructor fn is object, return this object.
// Otherwise return the `instance`.
return typeOf( return_val ) == 'object' ? return_val : instance;
}
// set the prototype object
// inherit properties & methods from the parent class
constructor.prototype = extend( {}, parent, prototype );
// set name to all annonymous functions
for ( var name in constructor.prototype ) {
if ( typeof( constructor.prototype[ name ] ) == 'function' ) {
// set the same name as the key
constructor.prototype[ name ].__name__ = name;
}
}
// make parent method calling available via `this.parent()`
constructor.prototype.parent = function () {
var fn = parent[ arguments.callee.caller.__name__ ];
if ( typeof fn !== 'function' ) {
throw new Error('Cannot call `parent`');
}
return fn.apply( this, arguments );
}
return constructor;
}