Skip to content

Instantly share code, notes, and snippets.

@atulgosain
Forked from rauschma/callable-instances.js
Last active February 11, 2025 14:07
Show Gist options
  • Select an option

  • Save atulgosain/f00fd55becbbc47ebaba32911e7e87af to your computer and use it in GitHub Desktop.

Select an option

Save atulgosain/f00fd55becbbc47ebaba32911e7e87af to your computer and use it in GitHub Desktop.
// Experiment: I’m not sure if I would use this myself.
//Just added a comment for practice
const call = Symbol('call');
class Callable {
constructor() {
// Can’t use .bind() here. Not sure why. Maybe the result doesn’t
// interact well with Object.setPrototypeOf().
const _this = (...args) => new.target.prototype[call].call(_this, ...args);
Object.setPrototypeOf(_this, new.target.prototype);
return _this;
}
}
class Frobnicator extends Callable {
constructor(x, y) {
super();
this.x = x;
this.y = y;
}
[call](z) {
return z * this._product;
}
// Can’t use private slots (which can only be accessed via original instance)
get _product() {
return this.x * this.y;
}
}
const ten = new Frobnicator(2, 5);
console.log(ten(3), "thirty");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment