在原生不支持的旧环境中添加兼容的 Object.keys

 1 if (!Object.keys) {
 2   Object.keys = (function () {
 3     var hasOwnProperty = Object.prototype.hasOwnProperty, //原型上的方法,只取自身有的属性;
 4         hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), //ie6一下,!之后的内容为false;
 5         dontEnums = [
 6           'toString',
 7           'toLocaleString',
 8           'valueOf',
 9           'hasOwnProperty',
10           'isPrototypeOf',
11           'propertyIsEnumerable',
12           'constructor'
13         ],
14         dontEnumsLength = dontEnums.length;
15 
16     return function (obj) {
17       if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
18 
19       var result = [];
20 
21       for (var prop in obj) {
22         if (hasOwnProperty.call(obj, prop)) result.push(prop);
23       }
24 
25       if (hasDontEnumBug) {
26         for (var i=0; i < dontEnumsLength; i++) {
27           if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
28         }
29       }
30       return result;
31     }
32   })()
33 };

 

posted @ 2017-09-10 19:34  不要熬夜  阅读(643)  评论(0编辑  收藏  举报