Skip to content

Instantly share code, notes, and snippets.

@bitfishxyz
Created January 19, 2020 03:25
Show Gist options
  • Select an option

  • Save bitfishxyz/e2d292aeb7c43b683f45176c6fc8bdc2 to your computer and use it in GitHub Desktop.

Select an option

Save bitfishxyz/e2d292aeb7c43b683f45176c6fc8bdc2 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