-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisConstructor.js
66 lines (57 loc) · 1.53 KB
/
isConstructor.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
import isFunction from './isFunction'
import isNativeFunction from './isNativeFunction'
/**
* 检测测试函数是否为构造函数
* ========================================================================
* @method isConstructor
* @since 0.2.0
* @category Function
* @param {*} fn - 要测试的(构造)函数
* @returns {Boolean} - fn 是构造函数,返回 true,否则返回 false;
* @example
*
* const fn = function(){};
* const ff = class {};
* const callback = () => {}
*
* isConstructor(fn) // -> true
* isConstructor(ff) // -> true
* isConstructor(callback) // -> false
* isConstructor(console.log) // -> false
*
* isConstructor(Math) // -> false
* isConstructor(Boolean) // -> true
* isConstructor(Array) // -> true
* isConstructor(Function) // -> true
* isConstructor(Date) // -> true
* isConstructor(RegExp) // -> true
* isConstructor(Object) // -> true
* isConstructor(Promise) // -> true
*/
const isConstructor = (fn) => {
let proto = null
let constructor = null
let instance
if (!isFunction(fn)) {
return false
}
proto = fn.prototype
if (!proto) {
return false
}
constructor = fn.constructor
if (
isNativeFunction(fn) &&
(constructor === Function || constructor === fn)
) {
return true
}
// 判断 fn 是否为 Promise 构造函数
instance = new fn()
// 判断 constructor
return (
(instance.constructor === fn && instance instanceof fn) ||
(instance.constructor === Object && instance instanceof Object)
)
}
export default isConstructor