3
function Box(width, height)
{
  this.width = width;
  this.height = height;
}

var myBox = new Box(5,5);
  1. 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?

  2. If so then this is a way to create a "Box", does this mean the this keyword is actually referring to the object myBox?

13
  • See here: quirksmode.org/js/this.html Commented May 28, 2013 at 16:23
  • 1
    basic principles of object oriented programming. better find a good starters guide to oop Commented May 28, 2013 at 16:24
  • 1
    @Sharky meh... This is JavaScript, "normal" OOP doesn't apply here imo. Valid question methinks. Commented May 28, 2013 at 16:25
  • 2
    stackoverflow.com/questions/133973/… 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. Commented May 28, 2013 at 16:32

1 Answer 1

11

It'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 recommend 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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.