Callable class
by mindplay
JavaScript
// Solution was found here:
// https://stackoverflow.com/a/54511133/283851
// This class is also a function:
class Hey {
constructor() {
function hey() {
return "hey";
}
this.value = "yo";
Object.assign(hey, this);
Object.setPrototypeOf(hey, Object.getPrototypeOf(this));
return hey;
}
yo() {
return this.value;
}
}
const hey = new Hey();
console.log(hey()); // it's callable π
console.log(hey.yo()); // methods are correctly bound to `this` π
console.log(hey instanceof Hey); // it type-checks π
// Inheritance works too:
class HeyHey extends Hey {
constructor() {
super();
}
yoyo() {
return this.value + "!";
}
}
const lol = new HeyHey();
console.log(lol()); // it's callable π
console.log(lol.yo()); // methods are correctly bound to `this` π
console.log(lol.yoyo()); // extension methods are correctly bound to `this` too π
console.log(lol instanceof Hey); // it type-checks π
console.log(lol instanceof HeyHey); // it type-checks π