javascriptclass

What is the use of the “this” keyword here?


class Rabbit1 {
  constructor(name, color, type) {
    if (arguments.length !== 3) throw new Error("Wrong length of arguments given");
    this.ar1 = name;
    this.ar2 = color;
    this.ar3 = type;
    this.testExtra = [];
    if (!name) {
      this.testExtra[0] = "This is in the constructor";
    } else {
      this.testExtra[0] = "Name is True";
    }
  }
  speak(line) {
    console.log(`The ${this.ar2} Rabbit, called '${this.ar1}'  and says it\ 's a ${this.ar3} rabbit, Oh and it\'s saying ${line} too... ${this.testExtra}`);
  }
  speak2(speak) {
    console.log("Hello " + this.ar1);
  }
}

let blackR = new Rabbit1(false, "black", "gentle");

blackR.speak("Hello");

I’m asking this question because, if you take a look at

if (!name)

The binding name is used, and it refers to the name of the instance of the class (in this case blackR).

So why do we use this.name when name on its own refers to the name value given in the instance of the class?


Solution

  • The binding name is used, and it refers to the name of the instance of the class (in this case blackR).

    No, it doesn't. name is the first parameter in the constructor:

    constructor(name, color, type) {
    

    The first value in the call is false:

    let blackR = new Rabbit1(false, "black", "gentle");
    

    So that is the value assigned to name. It's also assigned to this.ar1 in:

    this.ar1 = name;
    

    The code produces:

    "The black Rabbit, called 'false'  and says..."
    

    Which shows that this.ar1 has a value of false.

    So why do you we use this.name when name on its own refers to the name value

    The expression this.name does not appear in the OP. If you meant "Why is this.ar1 used instead of name", it's impossible to tell from the posted code. Within the constructor, they are essentially identical and have the same value.

    However, ar1 is a public property of the instance, so can be changed later.