Thread: Scope issue

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    16
    Rep Power
    0

    Scope issue


    I'm an enthusiastic novis who's trying to get my head around this:

    Code:
    //I've created a global array
    
    var stars = new Array();
    
    //I call a function that amongst other things populates that array with a new array 
    
    function reveal(a, b, c){
    //*snip*
    //that...should populate the global array, making all of these values global, right?
    
    	stars[0] = new Array();
    	stars[0][0] = 'orange';
    	stars[0][1] = cardx + stickers[cAlb][revCard][3];
    	stars[0][2] = revAnStp;
    	stars[0][3] = 30;
    	stars[0][4] = 15;
    	stars[0][5] = 0.8;
    	stars[0][6] = -0.5;
    	stars[0][7] = 0;
    
    	stars[1] = new Array();
    	stars[1][0] = 'yellow';
    	stars[1][1] = cardx + stickers[cAlb][revCard][3];
    	stars[1][2] = revAnStp;
    	stars[1][3] = 30;
    	stars[1][4] = 15;
    	stars[1][5] = 0.8;
    	stars[1][6] = 0.5;
    	stars[1][7] = 1;
    
    //I then call another function that draws the actual star
    	star(1);
    }
    
    function star(a){
    	context.fillStyle = stars[a][0];
    	// here's what I don't get:stars[a][7] will allways display 1.5, no matter how many times I call the function - as if I was creating a local variable. If I had written "var stars[a][7] =...." then fine, I could understand that it would be a local variable, but now it should just be a change to a global variable, right?
    	stars[a][7] = stars[a][7] + stars[a][6];
    	context.save();
    	context.beginPath();
    	context.translate(stars[a][1], stars[a][2]);
    	context.rotate(stars[a][7]*Math.PI/180);
    	context.moveTo(0,0-stars[a][3]);
    	for (var i = 0; i < stars[a][4]; i++){
    		context.rotate(Math.PI / stars[a][4]);
    		context.lineTo(0, 0 - (stars[a][3]*stars[a][5]));
    		context.rotate(Math.PI / stars[a][4]);
    		context.lineTo(0, 0 - stars[a][3]);
    	}
    	context.fill();
    	context.restore();
    }
    any help would be greatly appreciated
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    101
    Rep Power
    27
    Something not shown in your posted code is going on, I guess. Setting and overwriting a value in an array whose scope is global, will have an effect in every scope. Here is a small example.

IMN logo majestic logo threadwatch logo seochat tools logo