This probably has been asked before but all I can find are questions regarding C and Bash etc.
Basically I'm having a really hard time getting my head around function parameters and what they reference.
I know that you usually set paramters when you call the function e.g. doSomething(3,'Hello') etc, but when I read code from tutorials like so;
window.onload = initAll;
function initAll() {
if (document.getElementById) {
for (var i=0; i<24; i++) {
setSquare(i);
}
}
else {
alert("Sorry, your browser doesn't support this script");
}
}
function setSquare(thisSquare) {
var currSquare = "square" + thisSquare;
var colPlace = new Array(0,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4);
var colBasis = colPlace[thisSquare] * 15;
var newNum = colBasis + getNewNum() + 1;
document.getElementById(currSquare).innerHTML = newNum;
}
function getNewNum() {
return Math.floor(Math.random() * 15);
}
Where is setSquare() getting the parameter of thisSquare from?
5 Answers 5
In your first function initAll(), you are calling setSquare(i). In this case, the i is the parameter. According to initAll(), i is a number in the for loop. Essentially what's happening is you're calling setSquare for each square number 0 to 24.
The setSquare() function has renamed the i to thisSquare. Now anywhere inside the setSquare() function, thisSquare is set to the same value that i had before.
Hope that helps, good luck.
4 Comments
function definitions to the top of the scope. So before actually running the code, the interpreter translates it into something like this: pastie.org/3157006 Inside of initAll there is the following code:
for (var i=0; i<24; i++) {
setSquare(i);
}
So initAll is calling setSquare 24 times. Each time passing in the value of i. (0, 1, 2, etc.). So the value of i is thisSquare
Comments
setSquare is being called in the initAll function, which passes it a value, from 0 to 23. The initAll function is called when the page is loaded (in theory).
Comments
It is getting it from the for loop in the initAll() function in this case, but it could get it from wherever you call setSquare function
Comments
Where is setSquare getting the parameter of thisSquare from?
Right here: setSquare(i);
Inside the setSquare function currSquare ends up being the id of a Dom element (for example, currSquare1).
setSquare(i)? I'm not entirely sure what your question is.