views:

101

answers:

4

Hi guys,

I wrote a simple webpage as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>pop</title>
</head>
<body>
<script type="text/javascript" charset="utf-8">
document.write(this === window);
</script>
</body>
</html>

I browse this page using IE6 and FireFox 3.5.8, both give an answer true. But when I press F12 in FireFox and type this===window in the console, it will give me an answer false, why?

Great thanks.


So if this in firebug means the firebug object, how can I reference the normal this?

+3  A: 

Because Firebug is a Javascript program running inside of Mozilla. this in the Firebug console probably refers to the Firebug console itself.

Sean Vieira
+5  A: 

The this keyword inside firebug refers to the firebug object not the window object.

This is because of the scope of javascript execution.

Arun P Johny
+3  A: 

There is no normal this. It's context-dependent, and the context of Firebug is /not/ the global context. Other shells, such as Squarefree's, do run in the global context.

Matthew Flaschen
+1  A: 

So if this in firebug means the firebug object, how can I reference the normal this?

In your sample code this will be the window object because that is the Global Object when running in a browser. In Firebug the Global Object is Firebug itself (set a watch for both this and window in Firebug to confirm this).

From Douglas Crockford's A Survey of the JavaScript Programming Language:

There is a special variable, called this that is set to the object when a method of the object is called. ... In a simple function call, this is set to the Global Object (aka window)

Why are you trying to see if this is the window object anyway?

wrumsby