Skip to content

Instantly share code, notes, and snippets.

@jupegarnica
Forked from bitfishxyz/Singleton.js
Created February 12, 2020 14:28
Show Gist options
  • Save jupegarnica/cc815dd4dab8bdcbde8509948088e144 to your computer and use it in GitHub Desktop.
Save jupegarnica/cc815dd4dab8bdcbde8509948088e144 to your computer and use it in GitHub Desktop.
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