1

In the simple test code below I use a factory function to instantiate an object. When I examine its contents with Object.keys, Object.values & Object.entries it returns the values I expect.

"use strict"
 
function testFunction(x, y) {
    return {
        firstKey: x,
        secondKey: y
        }
}

let testObject = testFunction('ONE', 'TWO');  //generic factory function

console.log(Object.keys(testObject));
console.log(Object.values(testObject));
console.log(Object.entries(testObject));

When I instantiate the object with Object.assign it also works as expected.

"use strict"
 
function testFunction(x, y) {
    return {
        firstKey: x,
        secondKey: y
        }
}

let testObject = Object.assign(testFunction('ONE', 'TWO'));  //Object.assign test

console.log(Object.keys(testObject));
console.log(Object.values(testObject));
console.log(Object.entries(testObject));

However when I use Object.create to instantiate the object Object.keys, Object.values & Object.entries return empty arrays. This is not what I expect. Why is this happening? Why does a generic factory function and Object.assign return the predicted value but Object.create does not?

"use strict"
 
function testFunction(x, y) {
    return {
        firstKey: x,
        secondKey: y
        }
}

let testObject = Object.create(testFunction('ONE', 'TWO'));  //Object.create test

console.log(Object.keys(testObject));
console.log(Object.values(testObject));
console.log(Object.entries(testObject));
DR01D
  • 1,325
  • 15
  • 32

0 Answers0