<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type=text/javascript charset=utf-8> //发布者(被观察者) var Publish = function(name){ this.name = name ; this.subscribers = [];//所有的订阅者数组(每一个元素是函数类型fn) }; //发布者发布消息 Publish.prototype.deliver = function(news){//当成员函数看 var publish = this ; this.subscribers.forEach(function(fn){//fn是遍历过程中每一个元素 fn(news,publish); //把新消息发给一个订阅者 }); return this ; //return this 可以继续调用本函数或其他函数 }; Function.prototype.subscribe = function(publish){//当成员函数看 var sub = this; //some:数组的每一个元素,如果其中有一个返回true,那么整体返回true var alreadyExists = publish.subscribers.some(function(item){ return item === sub ; }); //如果当前出版社里不存在这个人 则将其加入其中 if(!alreadyExists){ publish.subscribers.push(this); } return this; //return this 可以继续调用本函数或其他函数 }; Function.prototype.unsubscribe = function(publish){//当成员函数看 var sub = this ; // filter (过滤函数:循环便利数组的每一个元素,执行一个函数如果不匹配,则删除该元素) publish.subscribers = publish.subscribers.filter(function(item){ return item !== sub ; }); return this; //链式编程 }; //发布者对象 var pub1 = new Publish('第一报社'); //观察者(订阅者) var sub1 = function(news){ //sub1当成函数地址,当成普通变量看,也就是sub1类型是函数类型而已。 alert(arguments[1].name + ':' + news + "sub1"); }; var sub2 = function(news){ alert(arguments[1].name + ':' + news + "sub2"); }; sub1.subscribe(pub1);//订阅就是加入到发布者的数组中 sub2.subscribe(pub1); pub1.deliver('text1'); sub1.unsubscribe(pub1); //取消订阅 </script> </head> <body> </body> </html>
Function.prototype:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type=text/javascript charset=utf-8> var Publish = function(name){ this.name = name ; }; Function.prototype.subscribe = function(){ //加载函数类型的变量上 alert(123); }; var g = function(){} g.subscribe();//123 var f = new Publish("sss"); f.subscribe();//f.subscribe is not a function function h(){} h.subscribe();//123 </script> </head> <body> </body> </html>