构造函数模式
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
var person = new Person('gaoyang')
person.sayName();
混合模式
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
function Student(name,age) {
Person.call(this,name);
this.age = age;
}
Student.prototype = Object.create(Person.prototype)
Student.prototype.sayAge = function(){
console.log(this.age)
}
var student = new Student('gaoyang','18')
student.sayName();
student.sayAge();
模块模式
var Person = (function(){
var name = 'gaoyang'
function sayName() {
console.log(name);
}
return {
name: name,
sayName: sayName
}
})()
Person.sayName()
工厂模式
function createPerson(obj){
var name = obj.name||'gaoyang'
function sayName() {
console.log(obj.name);
}
return {
name: name,
sayName: sayName
}
}
var person = createPerson({name: 'gaoyang'})
person.sayName();
单例模式
var Person = (function(){
var instance;
function init(){
return {name: 'gaoyang'}
}
function getInstance() {
if(!instance){
instance = init();
}
return instance;
}
return {
getInstance: getInstance
}
})()
console.log(Person.getInstance() === Person.getInstance())
发布订阅模式
var Person = (function(){
var events = {};
var oneEvent = {};
function on(event,handle){
events[event] = events[event] || [];
events[event].push({handle:handle})
}
function one(event,handle) {
oneEvent[event] = events[event] || [];
oneEvent[event] = {handle : handle}
}
function performance(event,name) {
if(events[event].length === 0){
return;
}
for(var i = 0;i<events[event].length; i++){
events[event][i].handle(name)
}
}
function performanceOne(event,name) {
if(oneEvent[event].length === 0){
return;
}
oneEvent[event].handle(name)
}
return {
on: on,
one: one,
performance: performance,
performanceOne: performanceOne
}
})()
Person.on('myEvent',function(name){
console.log(name)
})
Person.on('myEvent',function(name){
console.log(name)
})
Person.one('myEvent2',function(name){
console.log(name)
})
Person.one('myEvent2',function(name){
console.log(name)
})
Person.performance('myEvent','gaoyang')
Person.performanceOne('myEvent2','gaoyang2')
任务2
var Event = (function () {
var events = {};
function on(event,handle) {
events[event] = events[event] || [];
events[event].push({handle:handle})
}
function off(event) {
events[event] = [];
}
function fire(event,data){
if(events[event].length === 0){
return;
}
for(var i=0;i<events[event].length;i++){
events[event][i].handle(data)
}
}
return {
on: on,
off: off,
fire: fire
}
})()
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
//不执行它,会打印三次,第一个fire执行一次,第二个执行两次 ,,,,加上他执行两次,第一次执行完就置空了
Event.off('change');
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饥人谷');
网友评论