PDA

View Full Version : Add an array or variables to a class



filippo.ferrari
22 Oct 2010, 8:12 AM
Probably is simple but how to add a simple variable or an array in a class extended for use it in methods?

Eg.



class = Ext.extend(classUi, {


myvariable = 'x'
myaray

initComponent: function() {

ChiamateViewport.superclass.initComponent.call(this);

myGridPanel.on({'click' : mymethod, scope: this});

mymethod: function(){
console.log(myvariable)
}


});



(:|

jarrednicholls
22 Oct 2010, 9:50 AM
You can add the variable directly to the prototype, if it's a variable that could change from instance to instance.



MyClass = Ext.extend(MyClassUi, {
myVariable: 'x',
myArray: [],

initComponent: function() {
MyClass.superclass.initComponent.call(this);
console.log(this.myVariable);
}
});


or you can surround the class definition in a closure, if the variable is not meant to change from instance to instance and must remain "private" and untouched. This approach is very common in the singleton pattern:



(function() {
var myPrivateVar = 'x',
myPrivateArray = [];

MyClass = Ext.extend(MyClassUi, {
initComponent: function() {
MyClass.superclass.initComponent.call(this);
console.log(myPrivateVar);
}
});
})();


Note that the closure approach is strongly discouraged unless it absolutely "makes sense", because closures can be expensive performance wise.