3

Been searching for a while to fully understand how arrays works in object. I am familiar with other languages but this causes a lot of confusion for me. Having an object

var Test = {
    TestArray: [],
}
var a = Object.create(Test);
var b = Object.create(Test);

From my expectation this should create 2 instances of the object and having 2 different arrays however having an array inside behave like 1 instance adding values to the array affects both instances could anyone explain why?

1
  • 2
    Test isn't a class, it's an object. All you're doing is creating two objects a and b with the same shared prototype Test. Commented Nov 21, 2018 at 20:30

2 Answers 2

3

You are right, Object.create is creating a new object, but whenever you pass an object to it, it makes that object as a prototype of it.

Meaning, if that prototype object as an array, the will share the same instance.

Check out the example given in MDN, the function that they call is on the prototype, therefore there is only one instance of it.

In order to gain your request, you can use ES6 class syntax:

class Test {
  constructor() {
    this.TestArray = [];
  }
}

const t1 = new Test();
const t2 = new Test();

t1.TestArray.push('item1');
console.log(t1.TestArray);
console.log(t2.TestArray); // Should print an empty array

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

Comments

2

You're right about 2 instances of the object, but inside they have the same array reference, therefore mutating it in one place will mutate it in another place.

var Test = {
    TestArray: [],
}

var a = Object.create(Test);
var b = Object.create(Test);

a === b // false
a.TestArray === a.TestArray // true

There are quite a lot of ways to avoid this problem. Below is an option in order to keep Object.create

var getTest = () => ({
    TestArray: [],
});

var a = Object.create(getTest());
var b = Object.create(getTest());

1 Comment

Is there a other way to create array or the obect so they dont have same reference?

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.