dojo.declare secrets

A very short tuesday morning cookie for the ones who have been starving ;)

When using dojo.declare to build your own fancy widget there is one thing (besides others) you should keep in mind:
Arrays and objects as member variables are stored as references and not copies.

Lets look at a simple example

dojo.declare("calendar", null, {
    month: ["jan", "feb", "mar"],
    getMonth: function(index){
      if (this.month[index]){
        return this.month[index];
      }
    },
    setMonth: function(index, value){
      this.month[index] = value;
    }
});
 
var cal = new calendar();
var cal2 = new calendar();
 
console.log(cal.getMonth(0)); // jan
console.log(cal2.getMonth(0)); // jan
 
cal.setMonth(0, "JAN");
 
console.log(cal.getMonth(0)); // JAN
console.log(cal2.getMonth(0)); // JAN

You see that cal2 has its array changed as well and this is not what you always would like to happen.
To prevent this behavior, all you need to do is setting up a constructor method as following example shows:

dojo.declare("calendar", null, {
    month: [],
    constructor: function(){
      this.month = ["jan", "feb", "mar"];
    },
    getMonth: function(index){
      if (this.month[index]){
        return this.month[index];
      }
    },
    setMonth: function(index, value){
      this.month[index] = value;
    }
});
 
var cal = new calendar();
var cal2 = new calendar();
 
console.log(cal.getMonth(0)); // jan
console.log(cal2.getMonth(0)); // jan
 
cal.setMonth(0, "JAN");
 
console.log(cal.getMonth(0)); // JAN
console.log(cal2.getMonth(0)); // jan

Thats all :)

Tags: