3
votes

I'm learning to use dojo for a project I'm about to undertake and so confess in advance this is probably a very basic question. I've tried to find the answer but without success. Also, I'm having to use a slightly older version of dojo - 1.6 I think so without AMD.

I've delcared a class using dojo.declare, here is a slightly modified example:

dojo.declare("myNamespace.CustomClass", null, {
    firstProperty: "The default value",
    constructor: function () { }
    Test: function () {
        alert(this.firstProperty);
    }
});

So, essentially, a class called CustomClass with a public property called firstProperty that has a default value of "The default value", a constructor that doesn't currently do anything and a public method called Test that when called will alert with the value of firstProperty.

My assumption was that when I create an instance of CustomClass and call Test() I would get an alert box with "The default value". However, I don't, I get an alert box with "undefined" instead. If I set the value of firstProperty after the instance has been created and then call Test, it works and I get whatever the property had been set to. A way around would therefore be to set the default values in the constructor but what I've read suggests it should work the way I assumed so I'd rather do it correctly.

I've also tried calling dojo.safeMixin(this, null) in the constructor as something I read made my wonder if this was required, but it didn't make a difference.

Thanks in advance to anyway that reads this! Simon

1

1 Answers

5
votes

The key concept you are missing is the concept of scope. when you do alert(firstProperty);, you are referring to a local variable firstProperty. Which, in your case you have not defined any local variable wit that name. You have, however defined an instance variable with that name. Unlike in a language such as java, instance variables must be accessed explicitly using this.

So your example should be:

dojo.declare("myNamespace.CustomClass", null, {
firstProperty: "The default value",
constructor:function(params){
    console.log(params);
    dojo.safeMixin(this,params);
},
Test: function () {
    alert(this.firstProperty);
}

});

var myInstance = new myNamespace.CustomClass({firstProperty:'something else'});
myInstance.Test();

You might also want to take a look at Javascript Scope Tricks, since scope in javascript can get pretty tricky.

EDIT: I realized you weren't inherited from dijit._Widget. In that case, you need to manually apply the constructor parameters to the instance using dojo.safeMixin. I updated the code example above. I also created a simple jsfiddle demonstrating the code.