PDA

View Full Version : Proper Extend



r4nd7263
27 Jul 2011, 11:47 AM
Being a newbie to javascript and sencha touch, I am having trouble understanding the difference in these cases:

I declared MyNamespace.MyData class,



MyNamespace.MyData = Ext.extend(Object, {
myParam0 : -1,
myParam1 : "",

constructor : function(config) {
}
});
try to create a new instance,



var myData = new MyNameSpace.MyData({
myParam0 : 11,
myParam1 :"test"
});
when I do alert(myData.myParam0), it's -1. But if I change to



var myData = new MyNameSpace.MyData();
myData.myParam0 = 11;
myData.myParam1 = "test";
alert(myData.myParam0) shows 11.

How should I declare MyNamespace.MyData so I can create new object using the first method? Learning javascript as I go...probably not the best idea. :-|

mitchellsimoens
27 Jul 2011, 2:10 PM
You are doing the alert in the constructor I assume?

Every JavaScript Object has the constructor method and there are two sets of Objects that you can refer to... the config (param in the constructor method) and the one on this (scope). In your example of


var myData = new MyNameSpace.MyData({
myParam0 : 11,
myParam1 :"test"
});

Those two properties you are trying to set are on the config Object and has not been set to this.

r4nd7263
28 Jul 2011, 7:11 AM
I changed to



MyNamespace.MyData = Ext.extend(Object, {
myParam0 : -1,
myParam1 : "",
constructor : function(config) {
Ext.apply(this,config);
}
});
Seems to work, but is this correct?

mitchellsimoens
28 Jul 2011, 7:21 AM
If you are going to use constructor then yes, that is how you will have to do it. If you are going to use Panel or another Component, you can use initComponent and the config will already be applied to this.