I am new to Javascript, I have tried this:
object1 = {};
object2 = Object.create(object1, {a:{value:1}});
object2.a = 2;
Then if I display object2.a, it is still 1 instead of 2. why is that?
Thanks.
I am new to Javascript, I have tried this:
object1 = {};
object2 = Object.create(object1, {a:{value:1}});
object2.a = 2;
Then if I display object2.a, it is still 1 instead of 2. why is that?
Thanks.
because Object.create() is not what you think.
see this ECMAScript 5: Object creation and property definition
There are three additional aspects of a property we can control, each given a boolean value:
writable: Controls whether or not the property can be assigned. Iffalse, attempts at assignment will fail. Only applies to data descriptors.enumerable: Controls whether or not this property will appear infor...inloops.configurable: Controls whether or not the property can be deleted, and whether its property descriptor (other thanwritable) can be changed.Each of these defaults to
falseif not supplied.
so what you need is :
var object1 = {};
var object2 = Object.create(object1, {
a: {
value: 1,
writable: true
},
});
object2.a = 2;
Have fun : )
try this:
var object1 = {};
var object2 = Object.create(object1, {a:{value:1,writable: true}});
object2.a = 2;