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?