Home > Mobile >  in JS class, all this.var that are defined with functions, but they start without calling them
in JS class, all this.var that are defined with functions, but they start without calling them

Time:08-09

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;

enter image description here

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();

  • Related