工厂模式
function CreatePerson(name,age,sex) {
var obj = new Object();
obj.name = name;
obj.age = age;
obj.sex = sex;
obj.sayName = function(){
return this.name;
}
return obj;
}
var p1 = new CreatePerson("longen",'28','男');
var p2 = new CreatePerson("tugenhua",'27','女');
console.log(p1.name); // longen
console.log(p1.age); // 28
console.log(p1.sex); // 男
console.log(p1.sayName()); // longen
console.log(p2.name); // tugenhua
console.log(p2.age); // 27
console.log(p2.sex); // 女
console.log(p2.sayName()); // tugenhu
es6创建类模式:
//创建类的模式
class info{
constructor(name,age,min,max){
this.name = name
this.age = age
this.min = min
this.max = max
}
getNumber(){
return (this.min + this.max) / 2
}
}
var xiaoming = new info('小明',20,72,90,)
console.log(xiaoming.getNumber())
单例模式:
var info = {
name:'属性',
getli:function(){
console.log(1)
}
}
const s = info
s.getli()
jquery发布订阅者模式:
//简单理解就是把一连串的事情列一个清单,一件一件的执行下去:
//jquery发布订阅者模式:
let $pond1 = $.Callbacks() //创建一个事件池
$("#but").click(function(){
$pond1.fire()
})
let fn1 = function(){
console.log(1)
}
let fn2 = function(){
console.log(2)
}
let fn3 = function(){
console.log(3)
}
$pond1.add(fn1)
$pond1.add(fn2)
$pond1.add(fn3)
因为jquery有缺陷,自己封装发布订阅者模式(数组塌陷问题已经解决):
<script>
let _subscribe = (function(){
//发布订阅类
class Sub {
constructor(){
//创建事件池,用来存储后期执行的方法
this.$pond = []
}
//向事件池追加方法(重复处理)
add(func){
let flag = this.$pond.some(item => {
return item === func
})
!flag ? this.$pond.push(func) : null;
}
//从事件池移除方法
remove(func){
let $pond = this.$pond;
for(let i = 0; i < $pond.length; i++){
let item = $pond[i]
if(item === func){
$pond[i] = null
break;
}
}
}
//通知事件池方法按照顺序执行:
fire(...args) {
let $pond = this.$pond;
for (let i = 0; i < $pond.length;i++){
let item = $pond[i];
if(typeof item !== 'function'){
$pond.splice(i,1);
i--;
continue;
}
item.call(this,...args)
}
}
}
//返回供外部调用
return function subscribe() {
return new Sub()
}
})();
</script>
调用
let pond = _subscribe();
document.getElementById('but').onclick = function(ev){
pond.fire(ev);
}
let fn1 = function(){
console.log(1)
}
let fn2 = function(){
console.log(2)
pond.remove(fn1);
}
let fn3 = function(ev){
console.log(3,ev)
}
pond.add(fn1);
pond.add(fn1);
pond.add(fn2);
pond.add(fn3);
</script>
网友评论