1.写出 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例。
//构造函数设计模式
function People(name,age) {
this.name = name
this.age = age
}
People.prototype.sayName = function() {
console.log(this.name)
}
var student1 = new People('Jack',18)
var student2 = new People('jirengu',24)
student1 === student2 //false 两个不同的引用
//混合设计模式
function People(name, age) {
this.name = name
this.age = age
}
People.prototype.sayName = function () {
console.log(this.name)
}
function Student(name, age, score) {
People.call(this, name, age)
this.score = score
}
Student.prototype = create(People.prototype)
Student.prototype.constructor = Student
function create(parentObj) {
function F() { }
F.prototype = parentObj
return new F()
}
Student.prototype.sayScore = function () {
console.log(this.score)
}
var student1 = new Student('Jack', 18, 100)
var student2 = new Student('Peter', 28, 60)
student1 === student2//false,两个不同的引用
//模块设计模式
var Person = (function(){
var name = 'Jack'
function sayName(){
console.log(name)
}
return {
name: name,
sayName: sayName
}
})()
//工厂设计模式
function createPerson(opts) {
var person = {
name: opts.name || 'hunger'
}
person.sayName = function(){
console.log(this.name)
}
return person
}
var student1 = createPerson({name: 'Jack'})
var student2 = createPerson({name: ''})
student1 === student2 //false,不同的引用
//单例模式
var People = (function(){
var instance;
function init() {
var name = 'Jack'
var age = 18
return {
name: name,
age: age
}
}
return {
createPeople: function() {
if(!instance) {
instance = init()
}
return instance
}
}
})()
var student1 = People.createPeople()
var student2 = People.createPeople()
student1.name = 'Peter'
console.log(student2)//{name:'Peter',age:18}
student2.age = 30
console.log(student1)//{name:'Peter',age:30}
student1 === student2//true 指的是同一个引用
2.使用发布订阅模式写一个事件管理器,可以实现如下方式调用
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(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('changer');