开发者

JavaScript Globals - Method Handling

I have multiple global arrays that a single method performs operations on. The method will only need to operate on one array at a time. I would like to accomplish this by passing a parameter to the method and then let the method decide which array it needs to modify based on that parameter. For example,

var globalarray1;
var globalarray2;

Operate(globalarray1);

function Operate(globalarray){
   globalarray.push("test");
}

Of course, the code above only changes the value of the array local to the scope of the method. I know I can do something like this:

var globalarray1;
var globalarray2;

Operate(1);

function Operate(flag){
   if (flag == 1){
      globalarray1.push("test1");
   }
   else if (flag == 开发者_StackOverflow中文版2){
      globalarray2.push("test2")
   }
}

However, it just doesn't feel right. How can I change the value of the globals using parameters in a single method without using a bunch of conditional statements?


Your first approach is correct. This statement, however, is not:

Of course, the code above only changes the value of the array local to the scope of the method.

Array objects are passed by reference called by sharing (i.e. the reference is passed by value, not the value itself). When you pass the array to the method, it can (and in your case does) actually modified the global variable. This would not be the case if you passed in an immutable or primitive value such as a number or a string. In those cases, the value is in fact local to the scope of the method.

The fact that your variables are global have nothing to do with it. Take this code, for example:

function Hello(){
   var localArray = [];
   Operate(localArray);

   // now, localArray has been modified by Operate
}

Hello();

Above, localArray is not a global variable, but it can still be affected by Operate() if you pass the array in directly.


.push is a mutator method, and would change the array passed by the method since objects are passed by reference and not value in ECMAScript. So the first way is correct.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜