Global & Local variables in Javascript

2019-08-06 19:21发布

问题:

I have one variable and two functions . The variable is used by both. and the first function is changing the variable value (globally) each time it's used by it . This is what I want but it is not working with me .

x = 1;

function f1()
{
  x = x + 1;
  // use x 
} 

function f2()
{
  // use x
}

I've read other threads but x is always 1 which is very frustrating :|

added: actual code

<script type="text/javascript">

function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
return (S4() + S4() + ";" + S4() + ";" + S4() + ";" + S4() + ";" + S4() + S4() + S4());
}

P = '';

function Save() {
P = guid();
$('#btnBrowse').uploadifyUpload();
}

$(document).ready(function () {


            $('#txtText').elastic();

            $('#btnBrowse').uploadify({
                'uploader': '../uploadify.swf',
                'script': '../uploadify.ashx',
                'cancelImg': '/uploadify/cancel.png',
                'folder': '../images/Albums/',
                'multi': true,
                'fileDesc': 'Web Image Files (.JPG, .GIF, .PNG)',
                'fileExt': '*.jpg;*.gif;*.png',
                'scriptData': { 'Album_ID': P },
                'buttonText': 'Upload Images'
            });

});

</script>

so the variable is P . and it is used by jquery function (uploadify) . each time I excute Save function I expect I get a new value for variable P . But is always the same ??

回答1:

The problem is the time when you execute the code. The uplodify options are set on page load (which includes that P is passed on page load) and as P is a string, changing P later (through save()) will not change the value you passed.

You can solve this by passing a reference to the object as option, instead of the string Edit: Didn't work.

The plugin provides a uploadifySettings [docs] method to change the settings of an uploadify instance. Use it to update the scriptData settings:

function Save() {
    $('#btnBrowse').uploadifySettings('scriptData', {'Album_ID' : guid()}, true);
    $('#btnBrowse').uploadifyUpload();
}


回答2:

Maybe this fiddle can help you understand global scope a little better: http://jsfiddle.net/XFx27/1/

var x = 0;

function add1()
{
 x = x + 1;
}

function show()
{
    alert(x);
}

add1();
show(); //alerts 1
add1();
show(); //alerts 2

Your missing parens () after your functions function funcName()



回答3:

x = 1;

function f1()
{
  x = x + 1;
  // use x 
} 

function f2()
{
  // use x
}

// x is 1

f1();

// x is 2

f2();


回答4:

firstly, the f1 function should be:

function f1(){
   x = x + 1;
   // use x
}

var x;

function f1(){
    x = x + 1;
    console.log(x);
}

function f2(){
    console.log(x);
}

f1(); // 2
f2(); // 2

I tried the code in chrome console and I think it really works.