this in javascript



  • I'm a newcomer in javascipt, and I'm dealing with contexts and classes, and the context's kind of clear, and there's questions with classes.

    Why are we assigning variables through this.variable in the class designer, and call for functions through this.function, as in this example?

    class Rectangle {
      constructor(height, width) {
        this.height = height;
        this.width = width;
      }
    

    getArea() {
    return this.calcArea();
    }

    calcArea() {
    return this.height * this.width;
    }
    }

    Through this, can we announce a class variable copy? Can you explain what happens when you call this.height and what happens to class? How does the variable fit?



  • this - you can understand as an instinct of this clause. I mean, if you set up a prototype facility for this claus, this will be the very object, this.calcArea() is the method of the facility, and this.height will be the stack of the facility.

    const rect = new Rectangle(500, 500)
    

    Here. this - it's rect, this.height = 500, and the calcArea method will work directly with the values obtained above when applied and return 500 * 500.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2