SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru
    Join Date
    Jun 2004
    Location
    Finland
    Posts
    703
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Exclamation 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>
    The code above is an example of the problem and should be very self-explaining. The vars of AnotherMethod overwrite the vars of Method, which was called first. I have no idea why this happens, and I really don't want it to happen. Renaming the variables helps, but it is a very, very poor solution and does not work when recursing a function as follows:
    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>
    Now, if you have ANY idea how to prevent this from happening, PLEASE tell me. It'd be greatly appreciated.
    Last edited by Sorccu; Dec 23, 2004 at 09:50.

  2. #2
    SitePoint Addict
    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);

  3. #3
    SitePoint Guru
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •