I have been doing a lot of research on this lately, but have yet to get a really good solid answer. I read somewhere that a new Function() object is created when the JavaScr
The "global" scope of Javascript (at least in a browser) is the window
object.
This means that when you do this.myProperty = "foo"
and call the function as plain myFunction()
you're actually setting window.myProperty = "foo"
The second point with myFunction().myProperty
is that here you're looking at the return value of myFunction()
, so naturally that won't have any properties as it returns null.
What you're thinking of is this:
function myFunction()
{
myFunction.myProperty = "foo";
}
myFunction();
alert(myFunction.myProperty); // Alerts foo as expected
This is (almost) the same as
var myFunction = new Function('myFunction.myProperty = "foo";');
myFunction();
When you use it in the new
context, then the "return value" is your new object and the "this" pointer changes to be your new object, so this works as you expect.