代码改变世界

辅助函数

2017-08-20 16:32  彷徨在那里  阅读(295)  评论(0)    收藏  举报
 1 /**
 2  * obj 是否promise
 3  * 利用promise.then存在且为function
 4  */
 5 
 6 function isPromise(obj) {
 7   return 'function' == typeof obj.then;
 8 }
 9 
10 /**
11  * obj是否Generator
12  * 利用Generator的next 和 throw 两属性为Fuction的特点加以判断
13  */
14 
15 function isGenerator(obj) {
16   return 'function' == typeof obj.next && 'function' == typeof obj.throw;
17 }
18 
19 /**
20  * 是否Generator方法
21  * 利用constructor的name和displayName属性。
22  * @example
23  * var a = {}
24  * a.constructor === Object
25  * a.constructor.name // "Object"
26  */
27  
28 function isGeneratorFunction(obj) {
29   var constructor = obj.constructor;
30   if (!constructor) return false;
31   if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
32   return isGenerator(constructor.prototype);
33 }
34 
35 /**
36  * 判断是否干净对象 
37  * 利用constructor 属性。
38  * @example 
39  * Object.constructor === Object
40  */
41 
42 function isObject(val) {
43   return Object == val.constructor;
44 }