zoukankan      html  css  js  c++  java
  • 方法的链式调用【参考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);

    总结:

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

  • 相关阅读:
    Smarty学习笔记(二)
    Smarty学习笔记(一)
    MVC学习笔记(一)
    2015羊年主流手机配置什么样?
    FPGA学习笔记(一)Verilog语法基础
    FPGA学习笔记(二)模块建立及变量连接
    STM32学习笔记(一)时钟和定时器
    Win8 HTML5与JS编程学习笔记(一)
    Win8 HTML5与JS编程学习笔记(二)
    LUOGU P2831 愤怒的小鸟 (NOIP 2016)
  • 原文地址:https://www.cnblogs.com/samKR/p/3794253.html
Copyright © 2011-2022 走看看