-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
72 lines (57 loc) · 2.22 KB
/
index.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
function overridePropertyGetter(baseFn, context, fnName, propertyName) {
var descriptor = Object.getOwnPropertyDescriptor(context[fnName], propertyName);
if (descriptor && descriptor.configurable) {
Object.defineProperty(context[fnName], propertyName, {
get: function () {
return baseFn[propertyName];
}
});
}
}
function overrideFn(context, fnName, fn) {
if (typeof fnName === 'string') {
return overrideFnInternal(context, fnName, fn);
} else if (Array.isArray(fnName)) {
return fnName.map(function (name) {
return overrideFnInternal(context, name, fn);
});
} else {
var obj = arguments[1],
keys = Object.keys(obj);
return keys.reduce(function (result, key) {
result[key] = overrideFnInternal(context, key, obj[key]);
return result;
}, {});
}
function overrideFnInternal(context, fnName, fn) {
var baseFn = context[fnName] || function () {};
context[fnName] = function overrideFunction() {
var args = arguments,
params = Array.prototype.slice.call(args),
isCalledLikeConstructor = this instanceof overrideFunction;
params.unshift(function () {
var _args = arguments.length ? arguments : args,
_params = Array.prototype.slice.call(_args);
if (isCalledLikeConstructor) {
_params.unshift(this);
return new (Function.prototype.bind.apply(baseFn, _params));
}
return baseFn.apply(this, _params);
}.bind(this));
return fn.apply(this, params);
};
overridePropertyGetter(baseFn, context, fnName, 'name');
overridePropertyGetter(baseFn, context, fnName, 'length');
context[fnName].toString = function () {
return baseFn.toString();
};
return baseFn;
}
}
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = overrideFn;
} else if (typeof define === 'function' && define.amd) {
define('overrideFn', [], function () {
return overrideFn;
});
}