Unexpected shared data using JavaScript prototypal inheritance -


coming java background, expect properties in base class of instance of class unique other class instances use same base class.

in javascript, properties stored in "base class" appear shared between various instances of "base class". instance, see here:

http://jsfiddle.net/4waqv/

as can see, baseview.settings accessed via both viewone , viewtwo. changing value in baseview.settings in 1 instance affects value in other instance.

if move settings: {} out of baseview , viewone , viewtwo, works way expect.

http://jsfiddle.net/4waqv/1/

however, don't want clutter viewone , viewtwo properties. can dynamically create this.settings inside baseview.setprop():

http://jsfiddle.net/4waqv/2/

are there better ways deal this, or solution?

note i'm using backbone.js views in example, expect javascript prototype inheritance solution result similarly. can see backbone uses typical methods of creating prototypical inheritance:

https://github.com/documentcloud/backbone/blob/0.3.3/backbone.js#l870

https://github.com/documentcloud/backbone/blob/0.3.3/backbone.js#l955

the problem here settings inherited baseview; inherited, not copied. if string value copied, in javascript arrays , objects passed reference, not value, when object instantiates ends pointing @ same object.

the fix create initialize method in baseview , add line:

this.settings = {}; 

then of course you'll want make sure call baseview initialize each of subviews. can with:

baseview.prototype.initialize.apply(this, arguments); 

e.g. http://jsfiddle.net/taxilian/pdmn8/1/

note method of initializing members needs done on array or object members or you'll have same issue. create constructor , there, i've never been clear on how work in backbone classes , haven't taken time sit down , figure out =]


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -