3

hey after looking in mdn Object.create() MDN Im trying to duplicate their example but it doesnt work

here is what I tried and what I got

    const oTest = {a:1,b:2}
 
    const test1 = Object.create(oTest)
 
    console.log(oTest)  //{a: 1, b: 2}
    console.log(test1 ) //{}

I expected test1 to console {a: 1, b: 2}

Community
  • 1
  • 1
elad BA
  • 1,760
  • 11
  • 17

4 Answers4

2

As the comments said, the existing object is used as the prototype for the new created object. So you do not see it in a console.log (at least in Node). Try it in chrome and will this that the __proto__ has your oTest object. enter image description here

If you want to copy the object properties in your new object you can const test2 = {...oTest}. It is the spread operator : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

BenoitVasseur
  • 772
  • 5
  • 8
0

Object.create(o) creates an empty object. Sure, one that inherits properties from o, but that just means they are available on access and don't actually get copied into own properties. Your console only shows the own properties - but if you expand the object, it should also show the prototype chain.

const oTest = {a:1,b:2};
const test1 = Object.create(oTest);

console.log(oTest) // {a: 1, b: 2}
console.log(test1) // {}
console.log(Object.getPrototypeOf(test1) == oTest) // true
console.log(test1.a) // 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

If you check it with Chrome Developer tools for example, you can see the prototype of the object and it's properties.

Or you can just console.log(test1.__proto__) to view those that way.

enter image description here

Mulperi
  • 1,450
  • 1
  • 14
  • 24
0

May be you need to use Object.assign() to create a copy of existing object.

const oTest = {a:1,b:2}

const test1 = Object.assign(oTest)

console.log(oTest) //{a: 1, b: 2}

console.log(test1) //{a: 1, b: 2}

Sandip
  • 40
  • 3