defineClass.js
1.87 KB
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
/**
* @fileoverview
* This module provides a function to make a constructor
* that can inherit from the other constructors like the CLASS easily.
* @author NHN.
* FE Development Lab <dl_javascript@nhn.com>
*/
'use strict';
var inherit = require('./inheritance').inherit;
var extend = require('./object').extend;
/**
* Help a constructor to be defined and to inherit from the other constructors
* @param {*} [parent] Parent constructor
* @param {Object} props Members of constructor
* @param {Function} props.init Initialization method
* @param {Object} [props.static] Static members of constructor
* @returns {*} Constructor
* @memberof tui.util
* @example
* //-- #1. Get Module --//
* var util = require('tui-code-snippet'); // node, commonjs
* var util = tui.util; // distribution file
*
* //-- #2. Use property --//
* var Parent = util.defineClass({
* init: function() { // constuructor
* this.name = 'made by def';
* },
* method: function() {
* // ...
* },
* static: {
* staticMethod: function() {
* // ...
* }
* }
* });
*
* var Child = util.defineClass(Parent, {
* childMethod: function() {}
* });
*
* Parent.staticMethod();
*
* var parentInstance = new Parent();
* console.log(parentInstance.name); //made by def
* parentInstance.staticMethod(); // Error
*
* var childInstance = new Child();
* childInstance.method();
* childInstance.childMethod();
*/
function defineClass(parent, props) {
var obj;
if (!props) {
props = parent;
parent = null;
}
obj = props.init || function() {};
if (parent) {
inherit(obj, parent);
}
if (props.hasOwnProperty('static')) {
extend(obj, props['static']);
delete props['static'];
}
extend(obj.prototype, props);
return obj;
}
module.exports = defineClass;