1

Let's say I have a class that looks like this

class Foo {
  bar() {
    console.log('bar');
  }

  baz() {
    console.log('baz');
  }

  // other methods...
}

and I want all of its methods to be unconditionally called whenever a new instance is created. How would I go about that?

I'm currently doing it by calling each method in the class constructor method

class Foo {
  constructor() {
    this.bar();
    this.baz();
    // other methods
  }

  bar() {
    console.log('bar');
  }

  baz() {
    console.log('baz');
  }

  // other methods...
}

here's a snippet of that

class Foo {
  constructor() {
    this.bar();
    this.baz();
    // other methods
  }

  bar() {
    console.log('bar');
  }

  baz() {
    console.log('baz');
  }

  // other methods...
}

new Foo();

Is there a better way to do this?

This seems to be the closest to what I want to achieve. It works by ditching class methods and using IIFEs in classProperties instead.

So something like this

class Foo {
  bar = (() => {
    console.log('bar');
  })()

  baz = (() => {
    console.log('baz');
  })()
}

new Foo();

and it works well on Chrome but the majority of other browsers don't yet have support for classProperties since they were added in ES9

My question is:

If I have a class with a number of methods in it, can I call all of them whenever a new instance of that class is created without having to call each individual method in the constructor method of that class?

In the context of this question, you can completely ignore the need to pass parameters to the methods. I don't need to pass any parameters to any of the class methods.

volt
  • 873
  • 7
  • 15
  • Just use a transpiler like [Babel](https://babeljs.io/repl/#?browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=MYGwhgzhAEBiD29oG8BQ1oCMwCdoF5oAKIgSgID4V0Nph4A7CeEAUwDoR4BzIgcmw4-pANw0AvqTKoa2AF4FiZStVp1GzNpx795wsRknTxMhqwDucRGRFA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.8.4&externalPlugins=), the last example you posted will work everywhere (tested in IE11 successfully) – blex Feb 22 '20 at 19:22
  • If the properties with iifes example meets your requirements in terms of behavior, it really calls into question why you're using a class in the first place – Aluan Haddad Feb 22 '20 at 19:50

2 Answers2

0

If the order in which you call the methods is not important, you can iterate dynamically over the properties of your created instance with Object.getOwnPropertyNames method:

class Foo {
  constructor() {
    return Object.getOwnPropertyNames (Object.getPrototypeOf (this))
        .filter(propName => (propName !== 'constructor' && typeof this[propName] === 'function'))
        .forEach(propName => this[propName]());
  }

  bar() {
    console.log('bar');
  }

  baz() {
    console.log('baz');
  }

  // other methods...
}
mgarcia
  • 4,746
  • 3
  • 13
  • 29
0

You can declare function this way:

bar = function() {
  console.log('bar');
};

And iterate values of new instance, check for functions and call them:

class Foo {
  constructor() {
    Object.values(this).forEach(value => {
      if (typeof value === 'function') {
        value();
      }
    });
  }

  nonFunctionProp = 'nfp';

  bar = function() {
    console.log('bar');
  };

  baz = function() {
    console.log('baz');
  };

  // other methods...
}

new Foo();
srgrcp
  • 53
  • 4