最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What does this refer to in a JavaScript function? - Stack Overflow

programmeradmin2浏览0评论
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?

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?

Share Improve this question edited May 28, 2013 at 16:28 Lews Therin 11k4 gold badges50 silver badges72 bronze badges asked May 28, 2013 at 16:22 edanielsedaniels 7785 silver badges24 bronze badges 13
  • 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
 |  Show 8 more ments

1 Answer 1

Reset to default 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 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?
发布评论

评论列表(0)

  1. 暂无评论