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

后端 未结 4 1985
小蘑菇
小蘑菇 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:27

    Object.keys() returns an array of strings, which are the object's own enumerable properties.

    Reflect.ownKeys(obj) returns the equivalent of:

    Object.getOwnPropertyNames(target).
                       concat(Object.getOwnPropertySymbols(target))
    

    The Object.getOwnPropertyNames() method returns an array of all properties (enumerable or not) found directly upon a given object.

    The Object.getOwnPropertySymbols() method returns an array of all symbol properties found directly upon a given object.

    var testObject = {};
    Object.defineProperty(testObject, 'myMethod', {
        value: function () {
            alert("Non enumerable property");
        },
        enumerable: false
    });
    
    //does not print myMethod since it is defined to be non-enumerable
    console.log(Object.keys(testObject));
    
    //prints myMethod irrespective of it being enumerable or not.
    console.log(Reflect.ownKeys(testObject));

提交回复
热议问题