1

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.

1
  • Take a look at this post about object creation patterns and you will have a much better understanding of the difference between object1 and object2 in your example. codeproject.com/Articles/687093/… Commented Oct 13, 2015 at 1:12

2 Answers 2

2

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:

  1. writable: Controls whether or not the property can be assigned. If false, attempts at assignment will fail. Only applies to data descriptors.
  2. enumerable: Controls whether or not this property will appear in for...in loops.
  3. configurable: Controls whether or not the property can be deleted, and whether its property descriptor (other than writable) can be changed.

Each of these defaults to false if not supplied.

so what you need is :

var object1 = {};
var object2 = Object.create(object1, {
    a: {
        value: 1,
        writable: true
    },
});
object2.a = 2;

Have fun : )

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. There is a sentence in the article "writable: Controls whether or not the property can be assigned. If true, attempts at assignment will fail. Only applies to data descriptors." I am confused by it, it said, if true, assignment will fail. but default is false, means assignment will be ok?. is there something wrong with that sentence? should "if true" be "if false"?
@totally: Indeed, that logic is messed up
@totally that's a mistake , sorry for that ; p
1

try this:

var object1 = {};
var object2 = Object.create(object1, {a:{value:1,writable: true}});
object2.a = 2;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.