I have a variable in a function
that I want to be accessible by other fu开发者_高级运维nctions. How would you do that?
You have to specify the object the property (variable) is added to (variables are always properties of some object).
If you want this new variable to be accessible to everything, then you add it to the window object, like this:
window.variablename = 'some value';
Or maybe like this:
function funcA() {
if(typeof funcA.variable == 'undefined') {
funcA.variable = 0;
}
else {
funcA.variable++;
}
}
function funcB() {
alert(funcA.variable);
}
funcA();
funcB(); //alerts 0
funcA();
funcA();
funcA();
funcB(); //alerts 3
(function () {
var a;
setA(1);
alert(getA()); // 1
function setA(value) {
a = value;
};
function getA() {
return a;
}
})();
please avoid global variables. if you have asynchronous calls via jquery, the usage of global variables may lead up to ambiguous behaviors.
精彩评论