奇技淫巧之Object.keys

今天在群里看到两个keys函数实现

abcd的实现:

var obj = {
     a:1,
     b:2,
     c:3
}
function keys(obj){
     var a = [], i = 0;
     for (a[i++] in obj);
     return a ;
}
console.log(keys(obj))

灰大的实现:

var obj = {
     a:1,
     b:2,
     c:3
}
function keys(obj){
     var a = [];
     for (a[a.length] in obj);
     return a ;
}
console.log(keys(obj))

好疯狂吧,用到for ( LeftHandSideExpression in Expression ) Statement 。我也不清楚,自己查ECMA。但我知道这实现是有问题的,Object.keys 只收集自身属性名,不收集继承自原型链上的。加之,IE6下对Object的一系列属性是不可遍历的,这时我们还要修正一下。下面才是正确的实现:

// by 司徒正美 https://github.com/RubyLouvre/mass-Framework/blob/master/browers/lang.js
     var DONT_ENUM =  "propertyIsEnumerable,isPrototypeOf,hasOwnProperty,toLocaleString,toString,valueOf,constructor" .split( "," ),
     hasOwn = ({}).hasOwnProperty;
     for ( var i in {
         toString: 1
     }){
         DONT_ENUM = false ;
     }
  
     Object.keys = Object.keys || function (obj){ //ecma262v5 15.2.3.14
             var result = [];
             for ( var key in obj ) if (hasOwn.call(obj,key)){
                 result.push(key)
             }
             if (DONT_ENUM && obj){
                 for ( var i = 0 ;key = DONT_ENUM[i++]; ){
                     if (hasOwn.call(obj,key)){
                         result.push(key);
                     }
                 }
             }
             return result;
         };

你可能感兴趣的:(奇技淫巧之Object.keys)