简体   繁体   English

改变函数内的全局变量值

[英]Changing global variable value inside function

Here is my simple scenario. 这是我的简单场景。 I have a variable defined inside the ready() function which assigns the first value. 我在ready()函数中定义了一个变量,它赋予第一个值。

I also have a function outside ready() . 我还有一个ready()之外的函数。 What I want to do is to use the changed variable inside my new function. 我想要做的是在我的新函数中使用更改的变量。

Here is my JavaScript code: 这是我的JavaScript代码:

var myFunction = function() {
    // I wanna change Vp value here and wanna 
    // use this function with the new value        
    Vp = "new value";

    myFunction2 (); 
};

$(document).ready(function () {

    var Vp = "first value asign";
    $('#btnAddCustomer').click(myFunction);

    var myFunction2 = function() {
        // I will use Vp variable here with new value
    };
});

Discard the var statement. 丢弃var语句。 It assigned the value to a new local variable, instead of the global variable. 它将值赋给新的局部变量,而不是全局变量。

Here: 这里:

var Vp = "first assigned value"
var myFunction2;

var myFunction = function() {
    // I wanna change Vp value here and wanna use this function with the new value        

    Vp =  "new value"
    myFunction2(); 

    };

$(document).ready(function () {

    Vp = "first value asign";

    $('#btnAddCustomer').click(myFunction);

    myFunction2 = function() {

    alert(Vp)

    };

});

Fiddle: http://jsfiddle.net/XGGvv/10/ 小提琴: http//jsfiddle.net/XGGvv/10/

NOW THAT WORKS. 现在工作。

A nice reading on JS variable scopes: http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/ 关于JS变量范围的一个很好的解读: http//coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM