How do I resolve the scope issue with my variables and/or functions?

157 Views Asked by At

I'm using Javascript within the programming environment of Max/MSP. Here's a basic overview of it's implementation in Max if you're interested. There's nothing particularly unusual there. Just some custom functions/methods available.

So I'm not entirely sure of my terminology here. I have this: var velData = MultiDimensionalArray(8, 16) declared globally, which is referred to in the function below.

Is it a global variable? Since it's calling a function, MultiDimensionalArray, does that make velData a function expression? Either way, I'm unable to access a variable from outside my function:

function list(y) {
    if (inlet == 1) {

        y = arrayfromargs(messagename,arguments);

        for (var i = 0; i < y.length; i++ ) {
            velData[row][i] = y;
        }   
    }

}

post(velData[0][0]);
post();

post() is the equivalent to console.log and post(velData[0][0]) works when it's inside the function but not outside of it. I thought that since velData is declared globally, I should be able to access it outside the function but I can't.

Here is the code on Jsfiddle - http://jsfiddle.net/estevancarlos/WHc5j/

Suggestions?

1

There are 1 best solutions below

1
On BEST ANSWER

"So I'm not entirely sure of my terminology here. I have this: var velData = MultiDimensionalArray(8, 16) declared globally, which is referred to in the function below. Is it a global variable?"

The velData variable is only declared globally if it is not inside some other function.


"Since it's calling a function, MultiDimensionalArray, does that make velData a function expression?"

No, a function expression has nothing to do with the invocation of a function. It has to do with the manner in which the function is created, which will have no impact on its invocation, aside from a narrow issue or two that has nothing to do with your question.


"Either way, I'm unable to access a variable from outside a loop in my function:"

Then the variable either is not global, or it is being created/initialized sometime after your loop runs.


"post() is the equivalent to console.log and post(velData[0][0]) works when it's inside the function but not outside of it."

Then it would seem that the function it is placed in that causes it to work is being invoked sometime after velData is initialized, whereas if you don't have it inside the function, it's invoked immediately and before velData is initialized.


"I thought that since velData is declared globally, I should be able to access it outside the function but I can't. Suggestions?"

If indeed it's global, then it does sound like a timing issue. You need to track down where and when velData gets its value, and make sure that no other code tries to use velData before that happens.