Thursday, September 30, 2021

Explaining "this" in Javascript Constructors

 What am going to attempt to do in this post is explain very briefly how "this" works and means particular to constructors in Javascript. I am only doing this because I have been thinking what the best way to explain it would be.


So given the below;


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


What we are saying is that, for each statement this.property the "this" is an object and the "property" is in the object group of "this". so another way to represent the above would be;


object = {
  firstName = "first",
  lastName = "last"
}


so object = this


If this is not clear let me know and I will clarify and expand a bit more. I just haven't shared in years and thought I go straight to the point and keep it short like a stackoverflow thing. :)