cachaito
6/30/2014 - 11:38 AM

Object.keys(obj) oraz Object.getOwnPropertyNames(obj)

zamiast pętli for in w ECMAScript 5 udostępniono f-cje Object.keys(obj) oraz Object.getOwnPropertyNames(obj). getOwnPropertyNames() list all "own" property names regardless of whether they are enumerable or not. Zapamiętać: non-enumerable properties are still detectable by the in operator and the hasOwnProperty. To detect whether a specific property is enumerable or not, you can use the propertyIsEnumerable method.

var obj = {
  name : 'Asia',
  age: 28,
  sex: 'female'
};

Object.keys(obj); //["name", "age", "sex"]
Object.getOwnPropertyNames(obj) //["name", "age", "sex"]

/* różnica między metodami */

var a = {};
Object.defineProperties(a, {
    one: {enumerable: true, value: 'one'},
    two: {enumerable: false, value: 'two'},
});

Object.keys(a); // ["one"]
Object.getOwnPropertyNames(a); // ["one", "two"]

/* Object.keys polyfill dla IE8 */
if (!Object.keys) {
  Object.keys = function(obj) {
    var keys = [];

    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        keys.push(i);
      }
    }

    return keys;
  };
}