Re: JScript scope: "myFunction" in window ?
- From: "dhtmlkitchen@xxxxxxxxx" <dhtmlkitchen@xxxxxxxxx>
- Date: Sun, 02 Sep 2007 06:53:49 -0000
On Aug 31, 4:19 pm, David Golightly <davig...@xxxxxxxxx> wrote:
On Aug 31, 3:57 pm, "dhtmlkitc...@xxxxxxxxx" <dhtmlkitc...@xxxxxxxxx>
wrote:
I'm trying to learn something about JScript engine.
I have the following example:
<script>(function() {
poop = "brown";
myFunction = function myFunction() {}
}) ();
alert( poop ); // "brown" in IE
alert( "myFunction" in window ); // false in IE.
alert( typeof myFunction ); // false in IE.
function asdf() {
alert( 'ddd' + myFunction); // doesn't run in IE.
}
</script>
<body onload='asdf()'>fdf</body>
<script>asdf(); // doesn't run in IE. </script>
but if I define:
window.myFunction = function myFunction() {}
I get: true for in operator, and "function" for typeof op.
poop variable gets resolved but myFunction doesn't unless you tack it
explicitly onto window.
What is IE doing here with the scope of function references? Where is
myFunction?
Garrett
--
Programming is a collaborative art.
My first guess is:
(function() {
myFunction = function myFunction() {};
})();
Here, although you'd think myFunction would first be declared as a
global variable (aka property of the "window" object), the right side
of the assignment operation actually evaluates first, so the function
"myFunction" gets declared within the scope of you closure and its
reference gets assigned to the name "myFunction", which by then is
defined in the closure's scope, so it never goes down the scope chain
to the "window" object. Assigning it as a property of the window
object in the first place will actually create a property on the
"window" object, so this behavior is as expected. (As strange as it
may seem.)
-David
I came to that assumption this morning shortly after I woke up.
It makes sense. It's an adverse affect to IE's interpreting a
FunctionDeclaration when it sees an Identifier in a
FunctionExpression,
You explained it very well, so I can't comment on it much more.
Garrett
.
- References:
- JScript scope: "myFunction" in window ?
- From: dhtmlkitchen@xxxxxxxxx
- Re: JScript scope: "myFunction" in window ?
- From: David Golightly
- JScript scope: "myFunction" in window ?
- Prev by Date: Re: FAQ Update 9.85 Dated 2007-08-31
- Next by Date: Re: General question about javascript V HTML form
- Previous by thread: Re: JScript scope: "myFunction" in window ?
- Next by thread: Re: Advice: how best to create an image
- Index(es):
Relevant Pages
|