前端设计模式

模块模式 用于简单的封装,只暴露出几个接口

var Person =(function(){
    var name = 'Zzzoe'
    function sayName(){
        console.log(name)
    }
    
    return {
        name: name,
        sayName: sayName
    }
})()

Person.sayName()  //Zzzoe
console.log(Person.name)

构造函数模式 较复杂的组件

function Person (name, age){
    this.name = name
    this.age = age
}
//在原型上添加方法
Person.prototype.sayName = function(){
  console.log(this.name)
}
Person.prototype.sayAge = function(){
  console.log(this.age)
}

var girl = new Person('zoe','22')
girl.sayName() //zoe
girl.sayAge()  //22

混合模式

function Person (name, age){
    this.name = name
    this.age = age
}

Person.prototype.sayName = function(){
  console.log(this.name)
}
Person.prototype.sayAge = function(){
  console.log(this.age)
}

Girl = function(name, age, height){
  Person.call(this,name, age)
  this.height = height
}

Girl.prototype = Object.create(Person.prototype)
Girl.prototype.sayHeight = function(){
  console.log(this.height)
}
var girl = new Girl('zoe','22','162')
girl.sayName()
girl.sayAge()
girl.sayHeight()

工厂模式 用于:简单的创建对象

function creatPerson(opts){
  var person = {
    name: opts.name || 'zoe'
  }
  person.sayName = function(){
    console.log(this.name)
  }
  return person
}
var a = creatPerson({name: 'lalala'})
var b = creatPerson({name: 'ppppp'})
a.sayName()
b.sayName()

单例模式

var People = (function(){ 
    var instance
    function init(){
        //do something
        return {}
    }
    return {
        createPeople: function(){
            if(!instance){ 
                instance = init()
            }
            return instance
        } 
    }
}())
var obj1 = People.createPeople()
var obj2 = People.createPeople()

发布订阅模式

var Event = (function(){
  var events = {}

  function on(evt, handler){
      events[evt] = events[evt] || []
      events[evt].push({
          handler: handler
      })
      console.log(events)
  }

  function fire(evt, args){
      if(!events[evt]){
          return
      }
      for(var i=0; i

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