开发者

How would you create a non localized variable in a function so that it is accessible by other functions in javascript?

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜