A
A
Aleksandr_ghost_232021-07-09 09:30:16
JavaScript
Aleksandr_ghost_23, 2021-07-09 09:30:16

Why is the output of `this` via constructor and via `set` completely different?

Good day everyone.
I came across one problem: I cannot set new values ​​for class properties through set .

Here's a little more detail:

class Example {

  constructor() {
    this.value_1 = 10;
    this.value_2 = 20;

    console.log("Through constructor");
    console.log(`value-1: ${this.value_1}\nvalue-2: ${this.value_2}`);
  }

  set set_value(newVal) {
    console.log("\nThrough set");
    console.log(`value-1: ${this.value_1}\nvalue-2: ${this.value_2}`);

    this.value_1 = newVal;
  }

  printValue() {
    console.log(`\nThrough method`);
    console.log(`value-1: ${this.value_1}\nvalue-2: ${this.value_2}`);
  }
};

const newExample = new Example();
Example.prototype.set_value = 30;
newExample.printValue();


That is, we need to set a new value for the value_1 property via set ,
but when outputting to the console, it does not see the class property, and when trying to set value_1 via set , it fails.

But I wanted to display the object itself through this in the construct itself, and output it through set and noticed that they are different.

class Example {

  constructor() {
    this.value_1 = 10;
    this.value_2 = 20;

    console.log(this);
  }

  set set_value(newVal) {
    console.log(this);
  }

  printValue() {
    console.log(this.value_1, this.value_2);
  }
};

const newExample = new Example();

Example.prototype.set_value = 30;


And as we can see: if we display an object through its initialization, then all properties are at the first nesting level, but its printValue method is in __proto__, and there is also a new value_1: 30 property that we tried to set via set .

But if we display this in set , we will see a different picture: this is completely different here - it does not see the class property, and sets the new value_1 property in its object.

And to get this new property, you need to access this long path:
this.constructor.prototype.value_1

So what is the essence of the question: why is the output of `this` through the constructor and through `set` completely different? And why, in order to get the new value of the property that we set through set , it is necessary to access such a long path: this.constructor.prototype.value_1?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-07-09
@Aleksandr_ghost_23

This is how it works thisin javascript. If you exaggerate, then thisinside the function, this is what comes before the dot when calling this function.
By doing so, you get and, accordingly, write a value there. If you want to write a value to , write . Everything is simple. Example.prototype.set_value = 30;this === Example.prototype

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question