方法的链式调用【参考javascript设计模式第6章】

对应经常使用jquery的朋友,方法的链式调用应该是已经很属性了,书上有模拟出一个很简单的类库代码,

见代码如下:

Function.prototype.method = function(name,fn){

  this.prototype[name] = fn;

  return this;

};

(function(){

  function _$(els){

    ........

  }

  /*Events  addEvent getEvent*/

  _$.method("addEvent",function(type,fn){

    .....

  }).method("getEvent",function(e){

    ......

  }).

  /*DOM replaceClass hasClass getStyle setStyle*/

  method("addClass",function(className){

    ......

  }).method("removeClass",function(className){

    ......

  }).

  /*Ajax load*/

  method("load",function(uri,method){

    ......

  });

  window.$ = function(){

    return new _$(arguments);

  }

})();

使其能支持链式调用,即在最后都return this,如果想把getter器也返回this,则只需要把取值器后的操作做到回调里,即:

function Person("name"){

  this.name = name;

}

Person.prototype = {

  setName:function(name){

    this.name = name;

    return this;

  },

  getName:function(func){

    func.call(this,name);

    return this;

  }

};

var p1 = new Person("sammy").setName("lulu").getName(console.log);

总结:

链式调用有助于简化代码编写工作,使代码更加简洁,易读,

原文地址:https://www.cnblogs.com/samKR/p/3794253.html