Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading