1

Here I have a simple code to understand how Object.create() works. Here I have a common object to be used as prototype which is prototypeObj.newObj is an object which has its prototype set to prototypeObj. Here I have another object called session which has a property called anotherObj, and anotherObj has the same prototype as newObj. But adding new value to a property called foo which resides in the prototype of anotherObj , affect newObj too. Why am I experiencing this behaviour?

Code:

var prototypeObj = {
  foo: [],
  addItemToFoo: function(add) {
    this.foo.push(add);
  }
}

function create(fooVal) {
  var myProto = Object.create(prototypeObj);
  myProto.foo = fooVal;
  return myProto;
}

var newObj = create([1, 2]); // initialized with [1,2]

session = {
  anotherObj: create(newObj.foo) // initialized with [1,2]
}

session.anotherObj.addItemToFoo(6); // pushed 6 to session.anotherObj.foo

console.log("newObj.foo is " + newObj.foo); // newObj also get 6 pushed to its foo property

console.log("anotherObj.foo is " + session.anotherObj.foo);

1 Answer 1

1

foo is an array, it works by reference.

anotherObj: create(newObj.foo)

You are copying the reference here, so both your old and new object will have the same array reference to insert elements in. If you want to have to different array references, you should first copy it like this create(newObj.foo.slice())

https://jsfiddle.net/x8ftnh82/

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

3 Comments

@AL-zami what about now?
@AL-zami great :), notice that this wouldn't have happened with an integer or string for example. But it would also have happened with other objects like { something: 1 }.
ya, objects are passed by reference... this makes sence now

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.