The requirement is to have an alias to a prototype function.
Currently I'm doing this, which is adding an additional function and execution context, when called, as opposed to just a reference:
class X {
x() {
// stuff
}
y() {
this.x();
}
}
Because I don't know how to do this, in es5:
function X() {
}
X.prototype.x = function () {
// stuff
}
X.prototype.y = X.prototype.x;
Is it possible?
There are multiple ways to do this. The easiest is doing just the same as without class syntax:
X.prototype.y = X.prototype.x;
If you insist on class syntax, ES2022 will have static blocks:
class X {
…
static {
// notice unlike a method definition, this creates an enumerable property
this.prototype.y = this.prototype.x;
}
}
If you need to limit yourself to ES2015, you can still provide the x method as y in various ways:
class X {
…
constructor() {
// notice this creates an own, enumerable property
this.y = this.x;
}
}
class X {
…
// notice this prevents assignments to `.y`
get y() {
return this.x;
}
}
You can do the same thing with classes as well, because they use the same underlying prototype-based structure.
So,
class X {
x() {
// stuff
}
}
X.prototype.y = X.prototype.x
works fine.
If you want to define it in the class, the only way is your approach:
class X {
x() {
// stuff
}
y(...args) {
return this.x(...args);
}
}
However, this will still behave differently if x is overridden in a subclass (which might actually be what you want, if you want a true alias).
How about you add y in the constructor?
class X {
constructor() {
this.y = this.x;
}
x() {
// stuff
}
}
Of course this will add it as an instance property; this should be no issue though because all instances simply hold a reference to the prototype method in their y.
If that does not meet your requirements I'm kindly asking for a clarification.
Here's how you add it to the prototype:
class X {
x() {
console.dir(this.__proto__);
}
}
X.prototype.y = X.prototype.x;
(new X).x();
(new X).y();