js常见的设计模式

构造函数模式

function Person(name,age){
      this.name = name
      this.age = age
}
Person.prototype.sayName = function(){
     console.log(this.name)
}
var people = new Person('fangfang',18)

混合模式

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

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

Student.prototype = object.create(Person.prototype)

//或者
function fn(obj){
    function F(){}
    F.prototype = obj
    return new F()
}

Student.prototype.saySex = function(){
      console.log(this.sex)
}

var lucien = new Student()


模块模式

function person(){
   var name = 'fangfang';
   function student(){
       console.log(name)
   }

   return {
        name:name,
        fn:student
   }
}
var obj = person()
obj.fn()


工厂模式

function factory(name){
    var person = {
         name:name,
         sayName:function(){
            console.log(name)
         }
    }
    return person
}
factory('cwh').name


单例模式

var people = (function(){
    var instance
    function init(name){
       return {
          name:name
       }
    }
    return {
         createPeople:function(name){
                 if(!instance){
                       instance = init(name)
                  }
                   return instance
          }
    }

}())

//只会调用一个值
people.createPeople('cwh')
people.createPeople('cwb')

发布订阅模式

var Event = (function(){    
            var obj = {};
            //obj{hello:[{handler:handler}]}
            function on(evt,handler){
                obj[evt] = obj[evt] || []
                console.log(obj)
                obj[evt].push({
                    handler:handler
                });
                console.log(obj)
            }
            function fire(evt,args){
                if (!obj[evt]) {
                    return 
                }
                for(var i=0; i

作业

var Event = function () {
    var events = {};
    function on(evt, handler) {
        events[evt] = events[evt] || [];
        events[evt].push({
            handler: handler
        });
    }

    function fire(evt, args) {
        if (!events[evt]) {
            return
        }
        for (let i = 0; i < events[evt].length; i++) {
            events[evt][i].handler(args);
        }
    }
    function off(name) {
        delete events[name]//删除对象上的属性
    }
    return {
        on: on,
        fire: fire,
        off: off
    }
}()


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