What is the difference between Reflect.ownKeys(obj) and Object.keys(obj)?

后端 未结 4 1982
小蘑菇
小蘑菇 2021-02-01 01:08

Testing them out in a real simple case yields the same output:

const obj = {a: 5, b: 5};
console.log(Reflect.ownKeys(obj));
console.log(Object.keys(obj));

// Re         


        
4条回答
  •  野的像风
    2021-02-01 01:13

    First, an example (ES6Fiddle):

    // getFoo is property which isn't enumerable
    var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
    my_obj.foo = 1;
    
    console.log(Object.keys(my_obj)); // console ['foo']
    console.log(Reflect.ownKeys(my_obj)); // console ['getFoo', 'foo']
    

    Here, Reflect.ownKeys() returns an array of the target object's own property keys. Namely, an array of all properties (enumerable or not) found directly upon the given object concatenated with an array of all symbol properties found directly upon the given object.

    Object.keys() will only return the enumerable properties.

    Enumerable properties are those that can be enumerated by a for...in loop, with the exception of properties inherited through the prototype chain. See the MDN description for more details.

    Summary:

    Reflect.ownKeys() is the equivalent of Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)) which will return both enumerable and non-enumerable properties

    whereas

    Object.keys() returns enumerable properties but does not return non-enumerable properties (which is a characteristic of Object.getOwnPropertyNames()).

提交回复
热议问题