1

I understand in how the this keyword works in that it is contextual to what it is being called in, that it can be bound etc. one thing I do not get though is in an example like this:

function Person(first, last, age, gender, interests) {
 this.name = {
 first,
 last
 };
 this.age = age;
 this.gender = gender;
 this.interests = interests;
};

what I assumed would happen here is this will attach to the window object and add those properties. what is making the "this" keyword work differently in this situation compared to the way I thought this worked in a method or a constructor function, where this is bound to the surrounding function?

asked May 28, 2018 at 2:48
2
  • 1
    depends on how you "call" Person Commented May 28, 2018 at 2:51
  • "it is contextual to what it is being called in" – no, it’s about how it’s called. Where the function appears doesn’t matter. (And it’s the opposite for arrow functions.) Commented May 28, 2018 at 2:53

2 Answers 2

2

Precisely, that when you invoke the Person function via the new operator it becomes a constructor, with this representing the newly created object by new.

In other words, think of new as creating a new empty object, and then invoke Person on this newly created object and finally returning it fully "constructed".

answered May 28, 2018 at 2:51
Sign up to request clarification or add additional context in comments.

Comments

1
answered May 28, 2018 at 2:53

1 Comment

As a matter of terminology, there is no such thing as an "ES5 class constructor". ES5 does not even have the notion of "class". And technically speaking, the function in and of itself is not a constructor, although it may be intended for use as such (in other words, to be invoked with new).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.