构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例
构造函数模式
function Person(name) {
this.name = name;
}
Person.prototype.tellName = function() {
alert('hello' + this.name);
}
var person = new Person('carl');
person.tellName(); // 'carl'
.
混合模式
function Person(name, gender) {
this.name = name;
this.gender = gender;
}
Person.prototype.sayName = function() {
console.log(this.name);
}
function Coder(name, gender, language) {
Person.call(this, name, gender);
this.language = language;
}
Coder.prototype = Object.create(Person.prototype);
Coder.prototype.sayLanguage = function() {
console.log(this.language);
}
var coder1 = new Coder('carl', 'male', 'JavaScript');
coder1.sayName(); // 'carl'
coder1.sayLanguage(); // 'JavaScript'
.
模块模式
var Person = (function() {
var name = 'carl';
function sayName() {
console.log(name);
}
return {
name: name,
sayName: sayName
}
})();
Person.sayName(); // 'carl'
.
工厂模式
function createPerson(name){
var person = {
name: name,
tellName: function(){
console.log(this.name);
}
};
return person;
};
var person1 = createPerson('carl');
person1.tellName(); // 'carl'
.
单例模式
var Person = (function() {
var instance;
function init(name) {
return {
name: name
}
}
return {
createPerson: function(name) {
if (!instance) {
instance = init(name);
}
return instance;
}
}
})();
var person1 = Person.createPerson('carl');
var person2 = Person.createPerson('johnson');
console.log(person1.name); // 'carl'
console.log(person2.name); // 'carl'
.
发布订阅模式
var EventCenter = {
var events = {};
function on(e, handler) {
events[e] = events[e] || [];
events[e].push({
handler: handler
});
}
function fire(e, args) {
if (!events[e]) return;
for (var i = 0; i < events[e].length; i++) {
events[e][i].handler(args);
}
}
function off(e) {
delete events[e];
}
return {
on: on,
fire: fire,
off: off
}
}
具体实现
function EventCenter() {
this.events = {};
}
EventCenter.prototype.on = function(eventType, handler) {
this.events[eventType] = this.events[eventType] || [];
this.events[eventType].push({
handler: handler
});
}
EventCenter.prototype.fire = function () {
var _args = [].slice.call(arguments);
var eventType = _args.shift();
if (!this.events[eventType]) return;
var handlerArgs = _args;
for (var i = 0; i < this.events[eventType].length; i++) {
this.events[eventType][i].handler.apply(this, handlerArgs);
}
}
EventCenter.prototype.off = function(eventType) {
delete this.events[eventType];
}
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', 'hello');
Event.off('change');
var textInput = document.querySelector('#textIntput');
var btn = document.querySelector('#btn');
var result = document.querySelector('#result');
var Event = new EventCenter();
Event.on('change', function(val) {
result.innerText = 'change... now value is ' + val;
});
textInput.addEventListener('keyup', function() {
Event.fire('change', textInput.value);
});
btn.addEventListener('click', function() {
Event.off('change');
});