SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
-
Dec 23, 2004, 09:47 #1
- Join Date
- Jun 2004
- Location
- Finland
- Posts
- 703
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Unwanted sharing of variables inside class functions
Let's go directly to the code:
Code:<script language="JavaScript" type="text/javascript"> var MyClass = { Method : function(num) { a = num; // a = 2 someValueINeed = MyClass.AnotherMethod(10); alert(a); // now a = 10! wtf? }, AnotherMethod : function(someNum) { a = someNum; return a; } }; MyClass.Method(2); </script>
Code:<script language="JavaScript" type="text/javascript"> var MyClass = { Method : function(num,preventEndlessRecursion) { a = num; if (preventEndlessRecursion) { // prevent endless loop :) MyClass.Method(5); alert(a); // a = 5! again, wtf? } } }; MyClass.Method(2,true); </script>
Last edited by Sorccu; Dec 23, 2004 at 10:50.
-
Dec 23, 2004, 11:54 #2
- Join Date
- Jul 2000
- Posts
- 201
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Try using var to declare separate variables:
HTML Code:var MyClass = { Method : function(num) { var a = num; // a = 2 someValueINeed = MyClass.AnotherMethod(10); alert(a); // now a = 10! wtf? }, AnotherMethod : function(someNum) { var a = someNum; return a; } }; MyClass.Method(2);
-
Dec 23, 2004, 12:14 #3
- Join Date
- Jun 2004
- Location
- Finland
- Posts
- 703
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Yes! Great, thanks! Reputation on it's way
Bookmarks