Jump to content

window.alert()


Allerious

Recommended Posts

Hello

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 comment
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 comment
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);
}
func1();

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

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) {
    console.log(text);
  }
}

window.alert('test1');
obj.alert('test2');

 

Link to comment
Share on other sites

  • 6 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...