Created
January 19, 2020 03:25
-
-
Save bitfishxyz/e2d292aeb7c43b683f45176c6fc8bdc2 to your computer and use it in GitHub Desktop.
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
| function proxy(func) { | |
| let instance; | |
| let handler = { | |
| construct(target, args) { | |
| if (!instance) { | |
| // Create an instance if there is not exist | |
| instance = Reflect.construct(func,args) | |
| } | |
| return instance | |
| } | |
| } | |
| return new Proxy(func, handler) | |
| } | |
| // example | |
| function Person(name, age) { | |
| this.name = name | |
| this.age = age | |
| } | |
| const SingletonPerson = proxy(Person) | |
| let person1 = new SingletonPerson('zhl', 22) | |
| let person2 = new SingletonPerson('cyw', 22) | |
| console.log(person1 === person2) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment