3

I'm trying to setup a base class and derived class with ExtJS using Ext.extend.

:Base Class:

var Base = Ext.extend(Object, {
    settings: {},
    constructor: function(args) {
        var baseArgs = { 'user': '', 'password': '' };
        Ext.apply(this.settings, args, baseArgs);
    }
});

:Derived Class:

var Derived = Ext.extend(Base, {
    constructor: function(args) {
        Derived.superclass.constructor.call(this, args);
    }
});

:Problem:

var test1 = new Derived({ 'user': 'blackey1', 'password': 'blackeypw1' });
var test2 = new Derived({ 'user': 'blackey2', 'password': 'blackeypw2' });

At this point test1.settings is equivalent to test2.settings (using blackey2 and blackeypw2) as if they are pointing to the same object, I'm looking to find how to create independent objects.

Thanks for any help!

artlung
  • 33,305
  • 16
  • 69
  • 121
Blackey
  • 698
  • 7
  • 14

1 Answers1

5

With your current code, the empty settings object is added to the prototype of Base, so that one settings object is shared by all instances of Base and any instances of classes derived from Base (like Derived). What you should do instead is create the empty settings object in Base's constructor function so that each instance gets its own settings object:

var Base = Ext.extend(Object, {
    constructor: function(args) {
        var baseArgs = { 'user': '', 'password': '' };
        this.settings = {};
        Ext.apply(this.settings, args, baseArgs);
    }
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Thanks for the answer. Can you please clarify the logic behind why the same instance of settings object is shared by all instances of Base, and Derived classes? This totally got me by surprise. One would normally expect that each Derived object would get it's own instance of settings. – Praveen Kumar Oct 12 '15 at 06:03
  • @PraveenKumar It's because of JavaScript's prototypal inheritance. See [this related question](http://stackoverflow.com/questions/4425318/javascript-object-members-that-are-prototyped-as-arrays-become-shared-by-all-cla). – JohnnyHK Oct 12 '15 at 13:57