admin管理员组文章数量:1389922
function Box(width, height)
{
this.width = width;
this.height = height;
}
var myBox = new Box(5,5);
What is the
new
keyword doing here technically? Is it creating a new function? Or is it creating a new object and applying the function to it?If so then this is a way to create a "Box", does this mean the
this
keyword is actually referring to the object myBox?
function Box(width, height)
{
this.width = width;
this.height = height;
}
var myBox = new Box(5,5);
What is the
new
keyword doing here technically? Is it creating a new function? Or is it creating a new object and applying the function to it?If so then this is a way to create a "Box", does this mean the
this
keyword is actually referring to the object myBox?
- See here: quirksmode/js/this.html – Jonathan M Commented May 28, 2013 at 16:23
- 1 basic principles of object oriented programming. better find a good starters guide to oop – Sharky Commented May 28, 2013 at 16:24
- 1 @Sharky meh... This is JavaScript, "normal" OOP doesn't apply here imo. Valid question methinks. – Lews Therin Commented May 28, 2013 at 16:25
- 2 stackoverflow./questions/133973/… – user1106925 Commented May 28, 2013 at 16:28
-
1
I don't think this question is worthy of an
open/close
war. This is basic information that has been explained many times on SO. – user1106925 Commented May 28, 2013 at 16:32
1 Answer
Reset to default 11It's creating a new object, using Box
as its constructor. The value of this
in this case (when the function is called with the new
keyword) is the new instance being constructed. This new object will inherit from whatever is defined as Box.prototype
(the default being Object.prototype
).
I said in this case, because in JavaScript the value of this
is determined by how the function is called. I remend reading the MDN page on this
for more information.
Note: if this question is supposed to be closed, it should have been as a duplicate. Here are some possible duplicate links that might also help you:
- How does the "this" keyword work?
- Javascript 'this' value changing, but can't figure out why
- this value in JavaScript anonymous function
- javascript this object
- How does "this" keyword work within a function?
本文标签: What does this refer to in a JavaScript functionStack Overflow
版权声明:本文标题:What does this refer to in a JavaScript function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744618176a2615858.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论