开发者

Global variables vs. passing a value into a function?

开发者 https://www.devze.com 2023-04-06 18:37 出处:网络
I\'m new to JavaScript, and have a simple (I presume) question regarding best practice开发者_如何学运维s for accessing variables in functions:

I'm new to JavaScript, and have a simple (I presume) question regarding best practice开发者_如何学运维s for accessing variables in functions:

When should I declare a global variable, as opposed to simple passing a value into a function?


Declaring a global variable should only be used as an option of last resort.

Global variables are bad in general and especially so in javascript. There is simply no way to prevent another piece of javascript from clobbering your global. The clobbering will happen silently and lead to runtime errors.

Take the following as an example.

// Your code
myParam = { prop: 42 };
function operateOnMyParam() {
  console.log(myParam.prop);
}

Here i've declared 2 global variables

  • myParam
  • operateOnMyParam

This might work fine while testing your javascript in isolation. However what happens if after testing a user combines your javascript library with my javascript library that happens to have the following definitions

// My code
function myParam() {
  console.log("...");
} 

This also defines a global value named myParam which clashes with your myParam. Which one wins depends on the order in which the scripts were imported. But either way one of us is in trouble because one of our global objects is dead.


There are many, many reasons.. but an easy one is.. The argument of a function only exists in the function, while it's running. A global variable exists all the time, which means:

  • it takes up memory until you manually 'destroy' it
  • Every global variable name needs to be unique
  • If, within your function.. you call another function.. which ends up calling the first function, all of a sudden you may get unexpected results.

In short: because the function argument only lives for a really short time and does not exist outside the function, it's much easier to understand what's going on, and reduced the risk of bugs greatly.


When dealing with framework-less JavaScript I'll store my simple variables and functions in an object literal as to not clutter up the global namespace.

var myObject = {
   variableA : "Foo",
   variableB : "Bar",
   functionA : function(){
      //do something
      //access local variables
      this.variableA
   }
}

//call functions and variables
myObject.variableA;
myObject.functionA();
0

精彩评论

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