开发者

What does 'this' refer to when the function that uses it is called as `new myFunction("Hello")`

开发者 https://www.devze.com 2023-02-01 20:33 出处:网络
function myFunction(message) { this.message = message; return this.message; } document.body.innerHTML = new myFunction(\"Hello\");
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开发者_C百科 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 new operator, you create a new instance of an object defined in the constructor function and this refers to the new object.

Old answer before the question was completely changed by the addition of the new keyword:

Since myFunction is not being called with the new keyword, or in the explicit context of another object, it is effectively: document.body.innerHTML = window.myFunction("Hello");

So this is the window object.

You can confirm this by editing the function to console.log whatever this is and then looking in Firebug.


If you call new myFunction("hello"), then this refers to a new "empty" object (it does not refer to the function!) that inherits from the functions prototype property (myFunction.prototype).

Such a function is also called constructor function and it is convention to start the name with a capital letter.

0

精彩评论

暂无评论...
验证码 换一张
取 消