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);