hh54188
hh54188

Reputation: 15626

How can I define a global variable in object-oriented javascript function better

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?

Upvotes: 0

Views: 3496

Answers (4)

Marlon León
Marlon León

Reputation: 170

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

Upvotes: 1

vol7ron
vol7ron

Reputation: 42099

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.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160181

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.

Upvotes: 0

jwchang
jwchang

Reputation: 10864

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.

Upvotes: 0

Related Questions