Weird behaviour of Object.create()

87 Views Asked by At

Can somebody explain what is going on here: code sample 1:

o2={b:10};
function classCreate(proto,o){
    return Object.create(proto,o);
}
var o1=classCreate({a:o2},{});
console.log(o1.a.b);  // prints 10

code sample 2:

o2={b:10};
function classCreate(proto,o){
    return Object.create(proto,o);
}
var o1=classCreate({},{a:o2});
console.log(o1.a.b);  //reference error

How does Object.create manage to mangle its scope when extending the final object?

1

There are 1 best solutions below

0
On

The second argument in Object.create should be an object of properties given in a very strict format. For example this would work:

var o1 = classCreate({}, {a: {value: o2}});

Read more about it here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties