.this and get

what is the .this and get benefit and uses ? I could not understand the W3school and MDN about both

The this keyword contains the value of an objects self. An essential part of how classes and objects work in a language involves their ability to have knowledge of themselves.

Let us suppose we have a triangle class

const Triangle = {
  side1: 5,
  side2: 4,
  side3: 9
}

Now we want to use the power of methods so that the Triangle class can give us its parameter. But a function has its own scope so we need a way for it to have an understanding of the object, and this is were this comes in:

const Triangle = {
  side1: 5,
  side2: 4,
  side3: 9,
  parameter: function() {
    return this.side1 + this.side2 + this.side3;
  } 
}

As for the set and get keywords, there purpose is more for security. Take a collaboration situation for example. You’re job was to create a large class to hold data for your project and this data is interconnected, because of this the data needs to be retrieved in a very specific way. The getter’s job is to retrieve data in the way needed so that others using your class have a minimal chance of gathering data incorrectly.

A quick example of a getter placed in the previous Triangle class could look something like this:

const Triangle = {
  side1: 5,
  side2: 4,
  side3: 9, 

  _parameter: function() {
    return this.side1 + this.side2 + this.side3;
  },

  get parameter() {
    return this._parameter();
  }
}

console.log(Triangle.parameter);
1 Like