James Andino
James Andino

Reputation: 25779

How to refer to Global name space in JS

What is the variable for JS global namespace does it have a reference and can I change it? (disclaimer yes I know that is terrible practice if I can)

Upvotes: 0

Views: 1281

Answers (4)

Andy E
Andy E

Reputation: 344567

In JavaScript that isn't running in ECMAScript 3.1 strict mode, you can refer to the global object using the keyword this, but only when not executing code inside a function that has an object context.

// In global scope:
alert(this.Math === Math);  //-> true

function test() {
    alert(this.Math === Math);
}

test();     //-> true

var someObj = {};
test.call(someObj); //-> false, `this` is `someObj`

In browsers, as other answers have mentioned, the window object is also the global object.

alert(this === window); //-> true
alert(this.alert === window.alert); //-> true

Upvotes: 1

mrk
mrk

Reputation: 5117

The global namespace has these names:

window // most often seen

top // in some cases

self

parent // in some cases

this // in some cases

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23142

The global namespace/object for Javascript in a browser is window. As far as I know, you can change it, but don't.

EDIT: I was mistaken. Thankfully, you can't change it (e.g. window = {}; has no effect, at least not in Chrome).

Upvotes: 1

Cameron
Cameron

Reputation: 98746

In the browser, it's accessible via window.

alert(window.document === document);    // true

I just tried to change it using assignment in Google Chrome, but surprisingly it had no effect.

Upvotes: 1

Related Questions