前端设计模式

构造函数模式

function Person(name) {
    this.name = name;
}

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

var person = new Person('gaoyang')
person.sayName();

混合模式

function Person(name) {
    this.name = name;
}

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

function Student(name,age) {
    Person.call(this,name);
    this.age = age;
}
Student.prototype = Object.create(Person.prototype)
Student.prototype.sayAge = function(){
    console.log(this.age)
}

var student = new Student('gaoyang','18')
student.sayName();
student.sayAge();

模块模式

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

工厂模式

function createPerson(obj){
     var name = obj.name||'gaoyang'
     function sayName() {
         console.log(obj.name);
     }
     return {
         name: name,
         sayName: sayName
     }
}
var person = createPerson({name: 'gaoyang'})
person.sayName();

单例模式

var Person = (function(){
    var instance;
    function init(){
        return {name: 'gaoyang'}
    }
    function getInstance() {
       if(!instance){
         instance = init();
       }
       return instance;
    }
    return {
        getInstance: getInstance
    }
})()
console.log(Person.getInstance() === Person.getInstance())

发布订阅模式

var Person = (function(){
    var events = {};
    var oneEvent = {};
    function on(event,handle){
        events[event] = events[event] || [];
        events[event].push({handle:handle})
    }
    function one(event,handle) {
        oneEvent[event] = events[event] || [];
        oneEvent[event] = {handle : handle}
    }
    function performance(event,name) {
       if(events[event].length === 0){
           return;
       }
       for(var i = 0;i

任务2

var Event = (function () {
   var events = {};
   function on(event,handle) {
       events[event] = events[event] || [];
       events[event].push({handle:handle})
   }
   function off(event) {
      events[event] = [];
   }
   function fire(event,data){
       if(events[event].length === 0){
           return;
       }
       for(var i=0;i

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