Why if I write a class with some variables inside the constructor that are defined to a function, they all start, without calling them?
Let's suppose I have this type of code
class Console {
constructor(text) {
this.log = console.log(text);
this.warn = console.warn(text);
this.error = console.error(text);
}
}
new Console("hello world").log;
like you see in this line:
new Console("hello world").log;
I only called the .log
method but they run all 3 ones. This can be dangerous if you think about it. What I should do?
CodePudding user response:
You are calling them inside the constructor
Try wrapping each in a function
class Console {
constructor(text) {
this.log = () => console.log(text);
this.warn = () => console.warn(text);
this.error = () => console.error(text);
}
}
// nothing
new Console("hello world").log;
// works fine
new Console("hello world").log();