0

Suppose I have a function:

function test(){

//should I define global variable here
//like window.arr=new Array()?

}

//can I define here
//window.arr=new Array()?

test.prototype.method01=function(){
//or here:window.arr=new Array()?
}

Of the three ways above, which one is better?

5
  • Just declare it outside of any function scope and you'll be all set. You don't even have to access the window object. Commented Mar 20, 2012 at 1:42
  • don't define it with var and it will global no matter what scope you create it in Commented Mar 20, 2012 at 1:49
  • @thescientist: it'll also be unclear where it was defined, so that's a bad idea, unless you want obfuscated code. Commented Mar 20, 2012 at 1:53
  • I should add I don't advocate that practice at all however, was just pointing out a fact about the language (albiet a bad one). As mentioned in the answers, always namespace/scope your variables as much as possible. Commented Mar 20, 2012 at 1:57
  • agreed, though I'm guilty of doing everything, either out of ignorance or for an acute reason. Commented Mar 20, 2012 at 2:34

4 Answers 4

1

If it's a global, you will more than likely want to define it outside of a function. This is because if it's global, you want it to be accessible by any/all functions.

JavaScript is interpreted as it comes in. If you define it outside the function it will be declared as it is interpreted, if it is called inside the function, it will be declared as the function is called.

Sign up to request clarification or add additional context in comments.

Comments

1

Global variables are bad idea in general. The best you can do, is minimize its effect. Create a single global variable and this variable will become yor application container, for instance:


var APP = {};

APP.my_array = [];

I recommend you to check JavaScript: The Good Parts

1 Comment

The Good Part's is an excellent resource. As well as all things Crockford.
0

You can define Global variable with above cases are all fine.

But the big difference is that you have to call functions to have that array

except the second case.

Comments

0

If you're going to define a global variable (somewhat questionable to begin with, even globals should be namespaced) don't do it somewhere difficult to track down--keep it at the top level, unindented, so it's easy to spot.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.