-
2 Nov 2011 9:08 PM #1
Unanswered: array within class does not retain scope????
Unanswered: array within class does not retain scope????
Hi,
The following code uses ExtJS4. I have created a custom class and defined a variable as an array.For two different instances of the class "a" and "b" the values are getting shared.
(1) The first array variable is defined as elements: []. The add method adds to the elements
(2) The second array variable is defined as elements: null. While adding I check if it is null then create a new array before pushing.
With (1) the array elements between both the instances get shared. I would like to understand why (1) does not work as expected.
Any insights will be helpful.
Thanks,
Anup.
Code:<html> <head> <script type="text/javascript" charset="utf-8" src="http://cdn.sencha.io/ext-4.0.7-gpl/ext-all.js"></script> <script> Ext.define('MyClass',{ className: '', elements1: [], elements2: null, add : function(obj) { if(this.elements2==null) this.elements2 = new Array(); this.elements1.push(obj); this.elements2.push(obj); }, displayCount : function() { alert('Elements 1 length: ' +this.elements1.length); }, displayCount2 : function() { alert('Elements 2 length: ' +this.elements2.length); }, nothing: null }); Ext.onReady(function () { a = new MyClass(); b = new MyClass(); a.className='Object A'; a.add(1); a.add(2); a.add(3); b.className='Object B'; b.add(4); b.add(5); a.displayCount(); // displays 5 for elements1 -- shouldn't it be 3 b.displayCount(); // displays 5 for elements1 -- shouldn't it be 2 a.displayCount2(); // displays 3 correctly b.displayCount2(); // displays 2 correctly }); </script> <head> <body></body> </html>
-
2 Nov 2011 11:59 PM #2Ext JS Premium Member
- Join Date
- Apr 2008
- Location
- Groningen - Netherlands
- Posts
- 1,017
- Vote Rating
- 23
- Answers
- 75
you must re-initialize your arrays in the constructor. See http://www.sencha.com/forum/showthre...someway-global
-
3 Nov 2011 12:02 AM #3Ext JS Premium Member
- Join Date
- Apr 2008
- Location
- Groningen - Netherlands
- Posts
- 1,017
- Vote Rating
- 23
- Answers
- 75
Like
Code:Ext.define('MyClass',{ className: '', elements1: [], elements2: null, constructor: function(config){ this.elements1 = []; this.elements2 = []; } , add : function(obj) { if(this.elements2==null) this.elements2 = new Array(); this.elements1.push(obj); this.elements2.push(obj); }, displayCount : function() { alert('Elements 1 length: ' +this.elements1.length); }, displayCount2 : function() { alert('Elements 2 length: ' +this.elements2.length); }, nothing: null }); Ext.onReady(function () { a = new MyClass(); b = new MyClass(); a.className='Object A'; a.add(1); a.add(2); a.add(3); b.className='Object B'; b.add(4); b.add(5); a.displayCount(); // displays 5 for elements1 -- shouldn't it be 3 b.displayCount(); // displays 5 for elements1 -- shouldn't it be 2 a.displayCount2(); // displays 3 correctly b.displayCount2(); // displays 2 correctly });


Reply With Quote