Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this refer to in a JavaScript function?

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?

like image 336
edaniels Avatar asked Aug 24 '26 10:08

edaniels


1 Answers

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:

  • 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?
like image 143
bfavaretto Avatar answered Aug 26 '26 23:08

bfavaretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!