-
-
Save jupegarnica/cc815dd4dab8bdcbde8509948088e144 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