前端常见的设计模式

构造函数模式

function Car(speed) {
  this.speed = speed
}
Car.prototype.accelerate = function () {
  return this.speed += 1
}
let run = new Car(0)

混合模式(将父元素的原型链赋值给空对象F,再将空对象F赋值给子元素的原型链来实现继承同时不覆盖子元素的原型链)

let Qq = function (user, password) {
  this.user = user
  this.password = password
}
Qq.prototype.gameId = function () {
  console.log(this.user)
}
let Lol = function (user, password, telphone) {
  Qq.call(this.user, password)
  this.telphone = telphone
}
function mix(parentObj) {
  function F() { }
  F.prototype = parentObj;
  return new F()
};
Lol.prototype = min(Qq.prototype)
Lol.prototype.login = function () {
  console.log('login')
}

工厂模式(每次调用函数都会返回不同的局部变量)

function shop(name) {
  let goods = {
    name: name || 'empty'
  };
  goods.price = function () {
    console.log('the ' + this.name + ' is free')
  }
  return goods
}
let g1 = shop('candy')
let g2 = shop('suger')

单例模式(调用第一次初始化返回值,以后再调用返回值不变)

let Single = (function () {
  let dream
  function init(who) {
    return {
      lover: who
    }
  }
  return {
    createLover: function (who) {
      if (!dream) {
        dream = init(who)
      }
      return dream
    }
  }
})()
Single.createLover('null')
Single.createLover('goddess')

发布订阅模式(自定义组件)

let Event = (function () {
  let evts = {};
  function on(evt, handler) {
    evts[evt] = evts[evt] || []
    evts[evt].push({
      handler: handler
    })
  }
  function fire(evt, args) {
    if (!evts[evt]) {
      return
    }
    for (let i = 0; i < evts[evt].length; i++) {
      evts[evt][i].handler(args)
    }
  }
  function off(evt) {
    delete evts[evt]
  }
  return {
    on: on,
    fire: fire,
    off: off
  }
})()
Event.on('change', function (val) {
  console.log('change...  now val is ' + val);
});
Event.fire('change', 'newchange');
Event.off('changer');

你可能感兴趣的:(前端常见的设计模式)