1

Coming from a Java background, I expect properties in the base class of an instance of a class to be unique from other class instances that use the same base class.

In javascript, any properties stored in "base class" appear to be shared between various instances of that "base class". For instance, see here:

http://jsfiddle.net/4waQV/

As you can see, BaseView.settings is accessed via both ViewOne and ViewTwo. Changing a value in BaseView.settings in one instance affects the value in the other instance.

If I move settings: {} out of BaseView and into ViewOne and ViewTwo, everything works the way I expect.

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

However, I don't want to clutter up ViewOne and ViewTwo with extra properties. So I can dynamically create this.settings inside BaseView.setProp():

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

Are there better ways to deal with this, or is this a good solution?

Note that I'm using Backbone.JS views in this example, but I expect than any javascript prototype inheritance solution would result similarly. You can see that Backbone uses fairly 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

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
Tauren
  • 26,795
  • 42
  • 131
  • 167

1 Answers1

1

The problem here is that settings is inherited from BaseView; inherited, not copied. If it were a string value it would be essentially copied, but in javascript arrays and objects are passed by reference, not by value, so when the object instantiates it ends up pointing at the same object.

The fix is to create an initialize method in your BaseView and add this line:

this.settings = {};

Then of course you'll want to make sure you call the BaseView initialize from each of your subviews. You can do that with:

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

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

Note that this method of initializing members needs to be done on all array or object members or you'll have the same issue. You could also create a constructor and do it there, but I've never been really clear on how those work in Backbone classes and haven't taken the time to really sit down and figure it out =]

taxilian
  • 14,229
  • 4
  • 34
  • 73