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?
-
1depends on how you "call" PersonJaromanda X– Jaromanda X2018年05月28日 02:51:57 +00:00Commented 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.)Ry-– Ry- ♦2018年05月28日 02:53:09 +00:00Commented May 28, 2018 at 2:53
2 Answers 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".
Comments
In your example above, the function is an es5 class constructor.
Hope this helps :)
1 Comment
new).