-
Notifications
You must be signed in to change notification settings - Fork 0
/
private.js
65 lines (64 loc) · 1.62 KB
/
private.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
// 保持所有私有数据的map
var map = new WeakMap();
// 默认的数据存取函数
var defaultFn = {
has: function(key) {
return !!this[key];
},
get: function(key) {
return this[key];
},
getAll: function() {
var keys = Object.keys(this);
var ret = {};
for (var i = 0; i < keys.length; i++) {
ret[keys[i]] = this[keys[i]];
}
return ret;
},
set: function(key, val) {
this[key] = val;
return this;
},
delete: function() {
map.delete(this);
return this;
}
}
/*
封装函数,主要实现this的传递,因为用户执行get/set等函数时,
this的值是Factory类型的对象,这时候我们需要根据当前this去map中取到真正的this,
然后传递到最后执行的函数中。用户在函数中只需要直接访问this即可。
@param {Object} {get: function() {}}
*/
function wrap(protoFns) {
var ret = {};
for (key in protoFns) {
if (protoFns.hasOwnProperty(key)) {
ret[key] = (function(fn) {
return function() {return fn.call(map[this],...arguments)};
})(protoFns[key]);
}
}
return ret;
}
function getFactory(fn, protoFns) {
function Factory() {}
// 对象生成器
Factory.create = function() {
if (this !== Factory) {
return Factory.create(...arguments);
}
var target = new Factory();
// 禁止操作Factory类型的对象
Object.freeze(target);
map[target] = new fn(...arguments);
return target;
}
// 挂载函数到原型
Object.assign(Factory.prototype, wrap(Object.assign(defaultFn, protoFns)));
return Factory;
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined' ) {
module.exports = getFactory;
}