Having a problem understanding what I will call a variable scope question for lack of a better description.
Say I have a page with two functions, one() and two(). The first function has a locally-scoped variable x with an object in it. This function builds an element, below, in the DOM and this element contains an onClick, which calls the second function, and needs to pass x to the second function as an argument. I.e. the second function needs access to the data that is scoped to the first function.
I have tried:
<something onClick="two(x);">
but this doesn't seem to work. I know that there is a way to make x global but I have found in my other languages that globally-scoped variables are discouraged as being dangerous.
-
1show me the coooooooode!jbabey– jbabey2011年09月29日 20:13:31 +00:00Commented Sep 29, 2011 at 20:13
-
1It would help if you posted some code, we could make suggestions. You can put var x = 'something' straight into a <script> tag before the functions are defined. That will make it global, but this is not a great idea if you don't have to do it.Brian Hoover– Brian Hoover2011年09月29日 20:14:31 +00:00Commented Sep 29, 2011 at 20:14
4 Answers 4
How about using closure:
function one()
{
var x = Math.random();
var el = document.createElement('div');
el.innerHTML='Hi!';
el.addEventListener("click", function(){two(x)}, false);
document.getElementById('myDiv').appendChild(el);
}
function two(text)
{
alert(text);
}
one();
1 Comment
Using a global variable within a function is not necessarily bad, but it is considered bad practice to place variables in the window scope, which is assumed if you don’t wrap your variables inside a function or object.
Consider this example:
(function() {
var x = 1;
function callback() {
alert(x);
}
function bind() {
x++;
elem.onclick = callback;
}
}());
Comments
You should read up on variable scope.
The function closure of one() has access to x. But since it exists in one() and not outside other functions will not have access to it. So you are putting two(x); in your onClick, which will try to resolve the x to a global scope. And there is no global x
You can easily fix this by making x global. Just place var x beside your functions.
Comments
to make x global declare it outside of the method
var x = 0
function one()
x=1
function two()
print x
x will print 1
2 Comments
{} and semicolons (;). Also, there's no print function in javascript (except involving a physical printer). Finally, the OP knows that there is a way to make x global but doesn't want to do that, for good reason.