Last active
December 7, 2020 20:17
-
-
Save wentout/e65f03a581573ed35d9bf8ee6e00f8d5 to your computer and use it in GitHub Desktop.
forkable instance example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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