Jump to content

Global Variables Used By Another Function


tinfanide

Recommended Posts

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><script>var x = 0;var y,z;function add(){    y = x;    document.getElementById("div").innerHTML = x++;    z = x;    }add.prototype.show = function(){    document.getElementById("d").innerHTML = (z - y);    }window.onload = function(){    show();}</script></head><body><input type="button" value="add" onclick="add()" /><div id="div"></div><div id="d"></div></body></html>

I want to check if x is incremented by 1 everytime, execute something.But now I am stuck by setting global variables.y and z seem to return NaN.

Link to comment
Share on other sites

You haven't defined the show() function as a global function, so when you call it in the onload event I wouldn't expect anything to happen. Just for saving a bit of stack memory and shorten your code, you should directly reference the show() function:

window.onload = show;

Aside from that, if you call the show() method before add() is called, y and z will be undefined.

Link to comment
Share on other sites

var x = 0;var z;function add(){y = x;document.getElementById("div").innerHTML = ++x;show();}function show(){if((x-y)==1){  alert(1);  }}

But in this case, how can I use prototype to bring the variabels in add() to show()?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...