前端常见设计模式

构造函数模式

function People(name,age) {
    this.name=name
    this.age=age
}
People.prototype.say=function(argument) {
    console.log(this.name+this.age)
}
new People('小明','27')

模块模式

var module=(function() {
    var name='小明'
    function sayName() {
        console.log(name)
    }
    return{
        name:name,
        sayName:sayName
    }
}())

工厂模式

function factory(args) {
    var people={
        name:args.name
    }
    people.say=function() {
        console.log(this.name)
    }
    return people
}
var p1=factory({name:'小明'})

混合模式

var Person = function(name, age) {
    this.name = name;
    this.age = age;
};
Person.prototype.sayName = function(){
  console.log(this.name);
}
var Student = function(name, age,  score) {
    Person.call(this, name, age);
    this.score = score;
};
Student.prototype = Object.create(Person.prototype);
student.prototype.constructor=Student

Student.prototype.sayScore = function(){
  console.log(this.score);
}
var student = new Student("小明", 28, 99);
console.log(student);

单例模式

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

var student=people.createPeople('小明')
people.createPeople('xxx')

订阅发布模式

var Event=(function() {
    var events={} ;  //{change:[{handler:function(){}},{handler:function(){}}]}

    var on=function(evt,handler) {
        events[evt]=events[evt] || []
        events[evt].push({
            handler:handler
        })
    };
    var fire=function(evt,args) {
        if (!events[evt]) { return }
        for (var i = 0; i < events[evt].length; i++) {
            events[evt][i].handler(args)
        }
    };
    var off=function (evt) {
        if (!events[evt]) { return }
        delete events[evt]
    }
    return {
        on:on,
        fire:fire,
        off:off
    }
}())

Event.on('change', function(val){
 console.log('change...  now val is ' + val);  
});
Event.fire('change', '小明');
Event.off('change');
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。 构造函数模式function...
    蛋黄肉阅读 248评论 0 0
  • 1. 写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。 构造函数模式 混合模式 模...
    Gia_Mo阅读 1,218评论 0 0
  • 前言: 面向对象的语言有一个标志,那就是它们都有类的概念,而通过类可以创建任意多个具有相同属性和方法的对象。ECM...
    徐国军_plus阅读 181评论 0 1
  • ——觉知生涯“潜能” 素来不喜看轻喜剧和娱乐类节目,觉得不过是一群人哗众取宠,无聊时制造点儿嬉...
    箫音声声阅读 186评论 1 1
  • 路径和捡垃圾垃圾垃圾广告很好后悔过实事求是。啦啦啦啦啦啦啦啦啦啦
    追梦不悔阅读 192评论 0 0