Answer the question
In order to leave comments, you need to log in
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();
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;
this.constructor.prototype.value_1
this.constructor.prototype.value_1
?
Answer the question
In order to leave comments, you need to log in
This is how it works this
in javascript. If you exaggerate, then this
inside 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 questionAsk a Question
731 491 924 answers to any question