1.写出构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
//构造函数模式
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
return '我是' + this.name + ',' + this.age + '岁了';
};
var student = new Person("小谷", 3);
student.sayName();
//混合模式
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 = create(Person.prototype);
function create(parentObj) {
function F() {
}
F.prototype = parentObj;
return new F();
}
Student.prototype.sayScore = function () {
console.log(this.score);
};
var student = new Student('小谷', 3, 90);
student.sayName();
student.sayScore();
//模块模式
//通过一个闭包来实现一个模块
var Person = (function(){
var name = 'jirengu';
function sayName(){
console.log(name);
}
return {
name:name,
sayName:sayName
}
})();
//工厂模式
function createPerson(name) {
var Person = {
name: name,
sayName: function () {
console.log(this.name);
}
};
return Person;
}
createPerson("饥人谷").sayName();
//单例模式
var Person = (function () {
var instance;
function init(name) {
return {
name: name
};
}
return {
createPerson: function (name) {
if (!instance) {
instance = init(name);
}
return instance;
}
}
}());
Person.createPerson("饥人谷"); //name:"饥人谷"
Person.createPerson("hello"); //name:"饥人谷"
//发布订阅模式
var EventCenter = (function () {
var events = {}; //存储所有的key/value
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(){
console.log('hello');
});
EventCenter.fire('hello');
EventCenter.off('hello');
2.使用发布订阅模式写一个事件管理器,可以实现如下方式调用
var Event = (function () {
var events = {}; //存储所有的key/value
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', '饥人谷');
Event.off('changer');