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
First, JavaScript doesn't behave the same way about objects as C++/Java does, so you need to throw those sorts of ideas out of the window to be able to understand how javascript works.
When this line executes:
var myFunctionVar = new myFunction();
then the this inside of myFunction() refers to this new object you are creating - myFunctionVar. Thus this line of code:
this.myProperty = "Am I an object!";
essentially has the result of
myFunctionVar.myProperty = "Am I an object!";
It might help you to take a look at some documentation on the new operator. In JS, the new operator essentially allows you to create an object out of a function - any plain old function. There is nothing special about the function that you use with the new operator that marks it as a constructor, as it would be in C++ or Java. As the documentation says:
Creating a user-defined object type requires two steps:
- Define the object type by writing a function.
- Create an instance of the object with new.
So what you have done with the code
function myFunction(){
this.myProperty = "Am I an object!";
}
is to create a function that would be useful as a constructor. The reason why the code myFunction.myProperty fails is that there is no reference named myFunction.