Bixel
Bixel

Reputation: 75

What is a global variable in JavaScript?

I'm from a C# Class(), fields, properties, namespace...world. And I just launched myself into javascript. So far I've been doing great. However one of my friends was looking at my code and asked me why I did this.

function Position (x, y) {
    this.X = x;
    this.Y = y; 
}

friend: "You've just over-rided Position..." me : "What Position?" friend: "Could be anything the browser is using." me : "I am only running this script - it works perfectly" friend: "Until it doesn't work."

Ok so... What? Turns out Position is Global .. but where and to what extent? My friend makes it sound like its Global to the entire browser. So my question is;

Is a javascript Global, Global to the Entire Browser? > The Window Only? > The Tab Only?? > how far does it go??

Upvotes: 2

Views: 164

Answers (3)

Jacob T. Nielsen
Jacob T. Nielsen

Reputation: 2978

It is global to the current window. Don't worry about other tabs, windows or iframes. That being said what I think he is trying to state is a good principle in JavaScript namely

Don't clutter up the global namespace

meaning that whatever you make global should not be much and it should be very intentional.

JavaScript has function scope (not block scope) and so an easy way to get around this is by wrapping everything in an immediately invoked function expression.

;(function () {

     function Position (x, y){
          this.X = x;
          this.Y = y;
     }

     // use Position here

}());

Upvotes: 4

Michael Geary
Michael Geary

Reputation: 28860

When JavaScript is running in a browser, a global variable is a property of the window object. Therefore, it is global to the current window only, not to other browser windows, tabs, frames, or iframes. Each one of those has its own window object.

There is no Position global built into JavaScript. Your friend's concern is probably that some other piece of code you include on your page may also define that same global. So one of those definitions (whichever is defined later) will overwrite the other.

Upvotes: 2

era86
era86

Reputation: 101

Position is accessible from everywhere in the browser window. In web terms, I believe the browser window is the highest scope you can go.

What your friend is probably saying is, if someone already defined an object named Position that exists in the global scope, your code just changed that behavior. In general, you will want to protect the global scope from any of your custom methods by namespacing.

Upvotes: 0

Related Questions