上次我们简单的说了下单例的用法,这个也是在我们java中比较常见的设计模式。
今天简单说下链式调用,可能有很多人并没有听过链式调用,但是其实只要我简单的说下的话,你肯定基本上都在用,大家熟知的jQuery中我们通常都是调用完一个函数后,我们直接就继续调用其他函数,而不需要再去new一个新的对象。这就是典型的链式调用。
首先我们列举个例子,说明下并非链式调用,给我们带来的不方便的地方:
- /**
- * 从一个实例引出立案时调用的需求
- */
- (function(){
- //创建一个cat
- function Cat(name){
- this.name = name;
- this.run = function(){
- document.write(name+ " start run");
- }
- this.stopRun = function(){
- document.write(name+ " stop run");
- }
- this.sing = function(){
- document.write(name+ " start sing");
- }
- this.StopSing = function(){
- document.write(name+ " stop sing");
- }
- }
- //测试
- var c = new Cat("abc");
- c.run();
- c.sing();
- c.StopSing();
- c.stopRun();
- })()
下面我们举个例子说明下链式调用的好处,从而和上边非链式调用做比较:
- /**
- * 从一个实例引出立案时调用的需求
- */
- (function(){
- //创建一个cat
- function Cat(name){
- this.name = name;
- this.run = function(){
- document.write(name+ " start run");
- return this;
- }
- this.stopRun = function(){
- document.write(name+ " stop run");
- return this;
- }
- this.sing = function(){
- document.write(name+ " start sing");
- return this;
- }
- this.StopSing = function(){
- document.write(name+ " stop sing");
- return this;
- }
- }
- //测试
- var c = new Cat("abc");
- c.run().stopRun().sing().StopSing();
- })()
以上两个例子也比较简单的说明了链式调用和非链式调用的区别。
那么下面我们模仿jquery做一个链式调用的例子:
- /**
- * 模仿jquery的链式调用
- */
- //为了类(Function)扩展函数,我们定义一个他的静态函数
- Function.prototype.method = function(name,fn){
- this.prototype[name] = fn;
- return this;
- };
- (function(){
- //还记得吗他是私有变量的写法
- function _$(els){};
- //准备方法
- _$.onready = function(obj,fn){
- if(obj){
- //按需求吧对象(_$)注册到window上
- obj.$ = function(){
- return new _$(arguments);
- }
- }else{
- //按需求吧对象(_$)注册到window上
- window.$ = function(){
- return new _$(arguments);
- }
- }
- fn();
- }
- //链式的对象增加jquery库提供的操作函数
- _$.method("addEvent",function(type,fn){
- fn();
- }).method("getEvent",function(fn,e){
- fn();
- }).method("addClass",function(className){
- fn();
- }).method("removeClass",function(className){
- fn();
- }).method("replaceClass",function(oldClass,newClass){
- fn();
- }).method("getStyle",function(el,fn){
- fn();
- }).method("setStyle",function(el,fn){
- fn();
- }).method("load",function(url,fn){
- fn();
- });
- //开始使用
- var com = {};
- _$.onready(com,function(){
- // $("div01").addEvent("click",function(){
- // alert("click Event");
- // })
- com.$("div01").addEvent("click",function(){
- alert("click Event");
- com.$(this).getEvent(function(){
- alert("click getEvent");
- })
- })
- })
- })()