Gan Gan - 6 months ago 8
Javascript Question

How can I stop pass by reference an object stored in prototype?

Can I define an object as a prototype member? If yes then how can I stop the call by reference of an instantiated object?

function MediaUser (){
}

MediaUser.prototype.oThumb = {sUrl: 'noImage.png'};

var oMediaUser = new MediaUser();
var oMediaUser2 = new MediaUser();

oMediaUser.oThumb.sUrl = "a.png";

console.log(oMediaUser2.oThumb.sUrl); // prints a.png

Answer

Everything you define in prototype is shared by all objects. You have to put that inside the constructor if you want it to be different for all instances:

function MediaUser (){
  this.oThumb = {sUrl: 'noImage.png'}
}

var oMediaUser = new MediaUser();
var oMediaUser2 = new MediaUser();

oMediaUser.oThumb.sUrl = "a.png";

console.log(oMediaUser2.oThumb.sUrl); // prints noImage.png