Add the same function twice to Javascript class with different names

Viewed 138

I want to add the same function twice to a Javascript class with two different function names.

So far I have come up with two ways how this can be implemented.

  1. Add function to prototype under a different name:
  class MyClass {

    computeN() {
      // do some computation here
    }

  }

  MyClass.prototype.computeM = MyClass.prototype.computeN;
  1. Add two functions. Call first from second:
  class MyClass {

    computeN() {
      // do some computation here
    }

    computeM() {
      return computeN();
    }

  }

The first solutions is no plain class syntax, and the second works, but I would rather have jsut one function call than a nested one. Also, my second solution may be harder to maintain if the naumber of arguments changes in the original function.

Is there a better solution for my little problem?

The motivation is that I am implementing a parser, where different specs use different names for the same data type (uint16, ushort, card16). So having alternative function names for processing these data types would make it easier to follow the different specs.

1 Answers

There's nothing wrong with your first approach adding a second property to the prototype object for the second method after the class declaration. Or if you want the enumerable flag to be false for the new method as it is for the original:

Object.defineProperty(MyClass.prototype, "computeM", {
    value: MyClass.prototype.computeN,
    writable: true,
    configurable: true,
    // (The default for `enumerable` is `false`)
});

But if you don't want to do that, you can do an instance property:

class MyClass {
    computeN() {
      // do some computation here
    }
    computeM = this.computeN;
}

That's using public fields, which is implemented in most major JavaScript engines and likely to be in the spec soon. If you don't want to rely on it:

class MyClass {
    constructor() {
        this.computeM = this.computeN;
    }
    computeN() {
      // do some computation here
    }
}

Those both create an enumerable property. If you want it to be non-enumerable:

class MyClass {
    constructor() {
        Object.defineProperty(this, "computeM", {
            value: this.computeN,
            writable: true,
            configurable: true,
            // (The default for `enumerable` is `false`)
        });
    }
    computeN() {
      // do some computation here
    }
}
Related