- 写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
//构造函数模式:new一个实例
function Person(name, age) {
this.name=name;
this.age=age;
}
Person.prototype.sayName= function () {
console.log(this.name)
};
var person1 = new Person("lisa",30);
//混合模式
function Person(name, age) {
this.name=name;
this.age=age;
}
Person.prototype.sayName= function () {
console.log(this.name)
};
function Student(name,age,score) {
Person.call(this,name,age);
this.score=score;
}
Student.prototype=Object.create(Person.prototype);
Student.prototype.sayScore = function () {
console.log(this.score)
}
var stuent1= new Student("andy","12","100");
//模块模式:通过闭包实现一个模块
var Person = (function () {
var name = "ruoyu";
function sayName() {
console.log(this.name)
}
return {
name:name,
sayName:sayName
}
})();
Person.sayName();
//工厂模式:每次返回一个对象;
function CreatePerson(name) {
var person={
name:name,
sayName:function () {
console.log(this.name)
}
};
return person;
}
CreatePerson("ruoyu").sayName();
//单例模式:应用场景=》弹窗
Person = (function() {
var instance;
function init(name) {
return {name:name}
}
return {
createPerson:function (name) {
if(!instance){
instance = init(name);
}
return instance
}
}
})();
Person.createPerson("andy");//{name: "andy"}
Person.createPerson("lili");//{name: "andy"}
//发布订阅模式
var EventCenter = (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(var 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
}
})();
EventCenter.on("hello",function (name) {
alert(name)
});
EventCenter.fire("hello","456");//alert=>456
EventCenter.fire("hello","123");//alert=>123
EventCenter.off("hello");//解除事件
EventCenter.fire("hello","123");//没有弹框
- 使用发布订阅模式写一个事件管理器,可以实现如下方式调用
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
Event.off('changer');
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(var 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
}
})();
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷'); //change... now val is 饥人谷
Event.off('change');//移除事件
网友评论