I encountered a strange problem today.
The good: I successfully changed a global var value from within a function(in other words the below example works fine when “passedVarName” is substituted with “a”).
The bad: When trying to pass the global var name “a” (rather than putting it directly in the function) it fails to work.
Below is what I can’t seem to get working:
(on click document should write “2” but instead writes “NaN” ?)
Javascript:
var a = 1;
function click(passedVarName){
passedVarName ++;
document.write(passedVarName)
};
HTML:
<a href="javascript:click('a')">Click this Button to alter global var "a".</a>
Passing a global variable as a param to a function creates a copy of that var inside the function. The global doesn’t change.
This example will generate the same output everytime you click on the first div:
However, it seems like if you pass your variable as a property of an object, pass that object to the function, and inside your function modify the variable, it has global effect :
Here is a jsFiddle that works: http://jsfiddle.net/2Ahdb/3/