Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    Jan 2013
    Posts
    10
    Thanks
    3
    Thanked 1 Time in 1 Post

    Javascript scope in multiple object instances

    Hi,

    My brain's hurting a bit, would anyone be kind enough to explain why this:
    Code:
    var myObj = function() {
    	var value;
    	init = function() {
    		value = 10;
    		function1();
    	}
    	function1 = function() {
    		alert(value);
    	}
    	return {
    		init : init
    	}
    };
    
    var inst1 = myObj();
    inst1.init();
    
    var inst2 = myObj();
    inst2.init();
    Works, but this:
    Code:
    var myObj = function() {
    	var value;
    	init = function() {
    		value = 10;
    		function1();
    	}
    	function1 = function() {
    		alert(value);
    	}
    	return {
    		init : init
    	}
    };
    
    var inst1 = myObj();
    var inst2 = myObj();
    inst1.init();
    inst2.init();
    Doesn't?

    Thanks in advance
    Last edited by Kyle123; 05-03-2013 at 03:01 PM.

  • #2
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    I think you're missing the "new" keyword when initializing your instances.

  • #3
    New Coder
    Join Date
    Jan 2013
    Posts
    10
    Thanks
    3
    Thanked 1 Time in 1 Post
    Thanks for your response, but it doesn't make any difference I'm afraid

  • #4
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    You initialize your inner functions at global, which causes interference. Make them local variables, too:

    Code:
    var myObj = function() {
    	var value;
    
    	var init = function() {
    		value = 10;
    		function1();
    	};
    
    	var function1 = function() {
    		alert(value);
    	};
    
    	return {
    		init : init
    	}
    };
    
    var inst1 = new myObj();
    var inst2 = new myObj();
    inst1.init();
    inst2.init();

  • Users who have thanked Airblader for this post:

    Kyle123 (05-03-2013)

  • #5
    New Coder
    Join Date
    Jan 2013
    Posts
    10
    Thanks
    3
    Thanked 1 Time in 1 Post
    Oh yeah, that was slack

    always the simple things. Thanks


  •  

    Posting Permissions

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