单例模式,简言之就是一个类无论实例化多少次,最终都是同一个对象
原生js的几个辅助方式的实现
- 手写forEch,map,filter
Array.prototype.MyForEach = function (callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
const arr = [1, 2, 3];
arr.MyForEach((item, index, arr) => {
console.log(item);
console.log(index);
console.log(arr);
});
Array.prototype.MyFilter = function (callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
const arr2 = [1, 2, 3, 5, 6, 7];
console.log(arr2.MyFilter((item) => item > 3));
console.log(arr2.MyFilter((item) => item < 5));
Array.prototype.MyMap = function (callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
console.log(arr2.MyMap((item) => item * 2));
基础单例模式
// 单体模式,
var SingleTon = {
a1: true,
a2: 10,
method1() {
console.log('单体模式1');
},
method2() {
console.log('单体模式2');
},
};
SingleTon.a1 = false;
let total = SingleTon.a2 + 5;
let result = SingleTon.method1();
// 全局命名空间
let GiantCorp = {};
GiantCorp.Common = {};
GiantCorp.ErrorCodes = {};
GiantCorp.PahgeHandler = {};
// 私有成员,一是相互约定用下划线标注
GiantCorp.DataParse = {
// 私有属性
_name: '张三',
// 私有方法
_getName() {
return this._name;
},
// 公有方法
getUsername(nickname) {
return this._getName() + nickname;
},
};
改进版单例
let MyNamespace = {};
// 使用闭包封装私有变量
MyNamespace.SingleTon = (function () {
let arr = ['张三', '李四', '王五'];
return {
name: '续航',
age: 18,
getName() {
return this.name;
},
getAge() {
return this.age;
},
getAllUserName() {
return arr.join(',');
},
};
})();
console.log(MyNamespace.SingleTon.getName());
console.log(MyNamespace.SingleTon.getAge());
console.log(MyNamespace.SingleTon.getAllUserName());
高阶版单例
// 惰性单体
let MyNamespace = {};
// 使用闭包封装私有变量
MyNamespace.SingleTon = (function () {
let singleTon = null;
function constructor() {
let arr = ['张三', '李四', '王五'];
return {
name: '续航',
age: 18,
getName() {
return this.name;
},
getAge() {
return this.age;
},
getAllUserName() {
return arr.join(',');
},
};
}
return {
getInstance() {
if (!singleTon) {
singleTon = constructor(); // 创建实例对象,并将其赋值给私有变量
}
return singleTon; // 返回实例对象(单例模式)
},
};
})();
console.log(MyNamespace.SingleTon.getInstance().getName());
console.log(MyNamespace.SingleTon.getInstance().getAllUserName());
案例
let simpleXhrFactory = (function () {
let standard = {
createXHRObject() {
return new XMLHttpRequest();
},
};
let activexOld = {
createXHRObject() {
return new ActiveXObject('Microsoft.XMLHTTP');
},
};
let activeXNew = {
createXHRObject() {
return new ActiveXObject('MSXML2.XMLHTTP');
},
};
let xhr = null;
try {
xhr = standard.createXHRObject();
return xhr;
} catch (e) {
try {
xhr = activeXNew.createXHRObject();
return xhr;
} catch (e) {
try {
xhr = activeXOld.createXHRObject();
} catch (error) {
throw new Error('不支持的浏览器');
}
}
}
return xhr;
})();