Skip to content

Instantly share code, notes, and snippets.

@wentout
Last active December 7, 2020 20:17
Show Gist options
  • Save wentout/e65f03a581573ed35d9bf8ee6e00f8d5 to your computer and use it in GitHub Desktop.
Save wentout/e65f03a581573ed35d9bf8ee6e00f8d5 to your computer and use it in GitHub Desktop.
forkable instance example
const Forkable = function () { };
Object.defineProperty(Forkable.prototype, 'fork', {
get () {
const me = this;
return function (...args) {
debugger;
// this keyword points to instance itself
if (new.target) {
return new me.constructor(...args);
}
return me.constructor.call(this, ...args);
};
}
});
const instance = new Forkable();
const forked = new instance.fork();
console.log(instance === forked); // false
console.log(instance instanceof Forkable); // true
console.log(forked instanceof Forkable); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment