As the title says, I have hit a conceptual snag in understanding how Object.create() works.
It was my impression that, after using this method, the resulting object would inherit the values of the object passed as argument to Object.create(). In the simple example below, I can create an object and access its inherited values, I can even correctly get the prototype of the new object, however the Object.keys() array is empty!
let obj = Object.create({x: 1, y: 2});
console.log("Keys of obj:");
Object.keys(obj).forEach(function (key) {
console.log(key + ' - ' + obj[key]);
});
console.log("Prototype of obj:");
console.log(Object.getPrototypeOf(obj));
console.log("obj.x = " + obj.x);
Console result:
acg@acg:~/dev/$ node test.js
Keys of obj:
Prototype of obj:
{ x: 1, y: 2 }
obj.x = 1
(Just to eliminate any confusion: I get the same results when substituting Object.getOwnPropertyNames() for Object.keys(), by the way).
Am I misunderstanding something? Why is the keys array empty?
EDIT: Am I right in assuming that Object.keys() and Object.getOwnPropertyNames() only give me the properties directly available on an object, i.e. not inherited? Then, I think my question is: is there a function that gives me an object's properties? (inherited or otherwise)
EDIT2: Nope -- got to traverse the prototype chain manually, as shown here: Is it possible to get the non-enumerable inherited property names of an object?
EDIT3: According to answer from Pol Martin below, one can use a for..in construct to loop over all properties (including those inherited). Also see https://stackoverflow.com/a/208439/7705625