function myFunction(message)
{
this.message = message;
return this.message;
}
document.body.innerHTML = new myFunction("Hello");
I learnt that “in JavaScript this always refers to the ‘owner’ of the function we’re executing, or rather, to the object that a function is a method of.” reference
In this example it would seem that the this in myFunction should refer to the owner of the myFunction then, the window. It seems like it’s referring to the myFunction though. Why is this?
When you use the
newoperator, you create a new instance of an object defined in the constructor function andthisrefers to the new object.Old answer before the question was completely changed by the addition of the new keyword:
SincemyFunctionis not being called with thenewkeyword, or in the explicit context of another object, it is effectively:document.body.innerHTML = window.myFunction("Hello");Sothisis thewindowobject.You can confirm this by editing the function toconsole.logwhateverthisis and then looking in Firebug.