We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。 这个可以类比浏览器中的 window 对象。有两个点需要注意:
window
简单来说就是,有个唯一的全局对象,供我们全局访问使用。
const mySingleton = function (name) { this.name = name this.instance = null } mySingleton.prototype.getName = function () { return this.name } mySingleton.getInstance = function (name) { if (!this.instance) { this.instance = new mySingleton(name) } return this.instance } const a = mySingleton.getInstance('qi') const b = mySingleton.getInstance('7') console.log(a.getName(), b.getName()) // qi qi console.log(a === b) // true
主要用于维护一个全局实例对象,减少频繁创建和销毁实例以及内存的占用。如:弹窗,第三方库等。
if (window.libName) { return window.libName } else { window.libName = '...' }
参考文章: JavaScript 设计模式(一):单例模式
The text was updated successfully, but these errors were encountered:
No branches or pull requests
定义
单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
这个可以类比浏览器中的
window
对象。有两个点需要注意:简单来说就是,有个唯一的全局对象,供我们全局访问使用。
实现
适用场景
主要用于维护一个全局实例对象,减少频繁创建和销毁实例以及内存的占用。如:弹窗,第三方库等。
参考文章:
JavaScript 设计模式(一):单例模式
The text was updated successfully, but these errors were encountered: