0

I have a local variable in my function. I want send my local variable to a global variable. For example this is my code

function moveToTop() {
    var manageTime=setInterval(function () {
        pacmanNowPosition=117//($('.pacman-down').data('top')+6);
        var pacmanOtherPosition=pacmanNowPosition-=18;
        console.log(pacmanOtherPosition)
        $('.pacman-down').css('top',pacmanOtherPosition).attr('data-top',pacmanOtherPosition);

    })
}

So guys I want every time send pacmanOtherPosition that is local to a global variable that is out of function.

3 Answers3

2

Global variables are accessible all the time. Just make the assignment while pacmanOtherPosition is in scope:

// Variables declared outside of functions with the `var` keyword are Global
var MyGlobal = null;

function moveToTop() {
  var manageTime = setInterval(function () {
    pacmanNowPosition=117//($('.pacman-down').data('top')+6);
    var pacmanOtherPosition=pacmanNowPosition-=18;
    console.log(pacmanOtherPosition)
    $('.pacman-down').css('top',pacmanOtherPosition).attr('data-top',pacmanOtherPosition);
    // Assign value to global here
    MyGlobal = pacmanOtherPosition;
  });
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Man do not work can you connect my pc and help me? thank you – سیدامیرحسین رسولی Jan 23 '18 at 23:43
  • @سیدامیرحسینرسولی The code I've shown is very simple and will work. If you are having a problem, it's because of some other issue with your code that is unrelated to your question. You should check the Console of your Developer's Tools window (F12) to see if there are errors. We do not connect to individual's PCs and fix issues for them. That's not what Stack Overflow is about. – Scott Marcus Jan 24 '18 at 15:03
0

A solution that will always work is to store it in an attribute of the window.

function f(){
   my_variable = 'hello';
   window.my_variable = my_variable;
}
Sylvan LE DEUNFF
  • 682
  • 1
  • 6
  • 21
-1

This was already asked before in here.

You could just declare the variable inside of the moveToTop function, but without the var keyword, which defines it in the global scope instead of the function's inner scope. Something like this:

pacmanOtherPosition = pacmanNowPosition -= 18;

As you see, no var before pacmanOtherPosition. Try accessing it outside of the function, and it will work.

Amit Beckenstein
  • 1,220
  • 12
  • 20