Jump to content

Recommended Posts


I'm starting the javascript tutorial and wondered what the purpose of window in window.alert() is?

If i remove window it does the same thing i.e an alert box appears at the top of the page. My guess is alert() is window by default and

there are other things that can be used in place of window to make the alert appear differently. Is this correct?

Link to post
Share on other sites

That's because you're always within the scope of the window. Anything that belongs to the window can be accessed without typing window unless a local variable or function of the same name exists.

Link to post
Share on other sites

there are other things that can be used in place of window to make the alert appear differently. Is this correct?

No, that's not correct.  All code in Javascript runs in a specific scope.  The scope is where it looks for defined functions and variables.  By default the global scope is the window object, so anything defined on the window object is available everywhere unless it's overwritten.  You can see scope in an example like this:

var a = 'foo';

console.log('global a:' + a);

function func1() {
  console.log('func1 a:' + a);

function func2() {
  var a = 'bar';
  console.log('func2 a:' + a);

If you run that and look at your browser's console, you'll see it print the different values.  The first 2 are the same.  Inside func1, since a is not redefined, it uses the global variable a.  In func2, a is redefined as a local variable, so it uses that instead.  That is scope, where things are defined.

Since the window is the default scope, you can refer to those variables and functions anywhere.  So window.alert is defined to show an alert box, but since window is the default scope you don't need to use it, you can just write alert and the browser will still go up the scope chain looking for a function called alert until it gets to the window object.  If you've seen document.getElementById, that's another example.  The document object doesn't live by itself, it's also a property of the window object.  So you could also write window.document.getElementById.

So, no, you can't just substitute something else for window and expect it to work.  It will only work if you've defined a function called alert on that object also:

var obj = {
  alert: function(text) {



Link to post
Share on other sites
  • 6 months later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...