本篇內容介紹了“JS實現單例模式的方式有哪些”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
一個實例只生產一次
保證一個類僅有一個實例,并提供一個訪問它的全局訪問點
利用instanceof判斷是否使用new關鍵字調用函數進行對象的實例化
function User() {
if (!(this instanceof User)) {
return
}
if (!User._instance) {
this.name = '無名'
User._instance = this
}
return User._instance
}
const u1 = new User()
const u2 = new User()
console.log(u1===u2);// true在函數上直接添加方法屬性調用生成實例
function User(){
this.name = '無名'
}
User.getInstance = function(){
if(!User._instance){
User._instance = new User()
}
return User._instance
}
const u1 = User.getInstance()
const u2 = User.getInstance()
console.log(u1===u2);使用閉包,改進方式2
function User() {
this.name = '無名'
}
User.getInstance = (function () {
var instance
return function () {
if (!instance) {
instance = new User()
}
return instance
}
})()
const u1 = User.getInstance()
const u2 = User.getInstance()
console.log(u1 === u2);使用包裝對象結合閉包的形式實現
const User = (function () {
function _user() {
this.name = 'xm'
}
return function () {
if (!_user.instance) {
_user.instance = new _user()
}
return _user.instance
}
})()
const u1 = new User()
const u2 = new User()
console.log(u1 === u2); // true當然這里可以將閉包部分的代碼單獨封裝為一個函數
在頻繁使用到單例的情況下,推薦使用類似此方法的方案,當然內部實現可以采用上述任意一種
function SingleWrapper(cons) {
// 排除非函數與箭頭函數
if (!(cons instanceof Function) || !cons.prototype) {
throw new Error('不是合法的構造函數')
}
var instance
return function () {
if (!instance) {
instance = new cons()
}
return instance
}
}
function User(){
this.name = 'xm'
}
const SingleUser = SingleWrapper(User)
const u1 = new SingleUser()
const u2 = new SingleUser()
console.log(u1 === u2);在構造函數中利用new.target判斷是否使用new關鍵字
class User{
constructor(){
if(new.target !== User){
return
}
if(!User._instance){
this.name = 'xm'
User._instance = this
}
return User._instance
}
}
const u1 = new User()
const u2 = new User()
console.log(u1 === u2);使用static靜態方法
class User {
constructor() {
this.name = 'xm'
}
static getInstance() {
if (!User._instance) {
User._instance = new User()
}
return User._instance
}
}
const u1 = User.getInstance()
const u2 = User.getInstance()
console.log(u1 === u2);“JS實現單例模式的方式有哪些”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。