-2

I came across understanding how 'this' worked in javascript with detail.

in w3school it explains how this works. (http://www.w3schools.com/js/js_object_definition.asp)

"The value of this, when used in a function, is the object that "owns" the function.

The value of this, when used in an object, is the object itself."

From my understanding, object constructors are functions, not objects, and according to the definition above 'this' within the constructor, should refer to the object that owns this constructor (on a global scale, that would be the window object).

However, the 'this' refers to the object constructor function. Why is that?

function person(first, last, age) {
   this.firstName = first;
   this.lastName = last;
   this.age = age;}

I've tried looking through other examples on stack overflow, but they don't seem to clear out this concept in detail.

peakersky
  • 81
  • 5
  • 5
    Don't rely on W3schools. In this case, both statements are either wrong or misleading, especially the second. In particular, there is no concept of "owning" in JS. It goes out without saying that `this` in the constructor refers to the object being constructed. –  Oct 12 '16 at 13:35
  • I dont think that's true. Maxim Egorushkin seems to have nailed the answer right on the answer below – peakersky Oct 12 '16 at 13:42
  • @Cerbrus It is not a duplicate IMO, the question you refer to is much more general, whereas this one is very specific. – Maxim Egorushkin Oct 12 '16 at 13:44
  • @MaximEgorushkin: The linked target explains _exactly_ how `this` works. after reading that, this question is redundant. – Cerbrus Oct 12 '16 at 13:46
  • @Cerbrus That would require reading a wall of text. And after reading a JavaScript book you would not need to read any answers here at all. – Maxim Egorushkin Oct 12 '16 at 13:48
  • @Maxim, we get dozens of _"how does `this` work?"_ questions per day. Most of them get closed as dupe of that target. This one is no different. – Cerbrus Oct 12 '16 at 13:49
  • You don't think what's true? –  Oct 12 '16 at 14:20
  • 1
    @MaximEgorushkin Perhaps you, or other people, including the OP, **should** read more walls of text. And read books--oh what a novel concept. Your view is that StackOverflow is a free "we read the books for you so you don't have to" service? –  Oct 12 '16 at 14:21

1 Answers1

0

In the constructor function invoked with new this refers to the object being constructed.

Maxim Egorushkin
  • 119,842
  • 14
  • 147
  • 239