学习Jquery的时候,我们通常会看到链式调用的写法

$(window).addEvent('load', function(){
    $('test').show().setStyle('color', 'red').addEvent('click', function(e){
        $(this).setStyle('color', 'yellow');
    });
});

下面用JavaScript来实现一个链式调用,核心思想是借助原型构造函数,在每个方法中return this。

(function(){
  function _$(els){
    this.element = [];
    for(var i = 0, len = els.length; i < len; i++){
      var element = els[i];
      if(typeof element === 'string'){
          element = document.getElementById(element);
      }
      this.element.push(element);
    }
    return this;
  }
  _$.prototype = {
    each: function(fn){
      for(var i = 0, len = this.element.length; i < len; i++){
        fn.call(this, this.element[i]);
      }
      return this;
    },
    setStyle: function(prop, val){
      this.each(function(el){
        el.style[prop] = val;
      });
      return this;
    },
    show: function(){
      var that = this;
      this.each(function(el){
        that.setStyle('display', 'none');
      });
      return this;
    },
    addEvent: function(type, fn){
      var add = function(el){
        if(window.addEventListener){
          el.addEventListener(type, fn, false);
        }else if(window.attachEvent){
          el.attachEvent('on' + type, fn);
        }
      };
      this.each(function(el){
        add(el);
      });
    }
  };
  window.$ = function(){
    return new _$(arguments);
  }
})();

下面用JavaScript来实现一个链式调用,核心思想是给Number对象原型添加属性和方法。

(10).add(10).reduce(2).add(10) 

Number.prototype.add = function(num){
    return this+num;
}
Number.prototype.reduce = function(num){
    return this-num;
}

最新文章

  1. mysql 基础
  2. PHP安全编程:不要让不相关的人看到报错信息
  3. WP8_检测列表是否滑动
  4. SharedPreferences实现记住密码功能
  5. Drupal如何实现类的自动加载?
  6. 学java入门到精通,不得不看的15本书
  7. 集成对象和 JSON
  8. Codeforces739E Gosha is hunting
  9. Apple Swfit UI控件实现
  10. WebConfig 配置文件详解
  11. TextView于getCompoundDrawables()使用演示样本的方法
  12. 由ASP.NET所谓前台调用后台、后台调用前台想到HTTP
  13. service_names配置不正确,导致dg创建失败
  14. qrcode生成二维码
  15. String、StringBuffer、StringBuilder区别
  16. python之线程相关操作(补充)
  17. C# 中删除控件的事件的方法类
  18. 关于System.getProperty(&quot;java.io.tmpdir&quot;);的输出,及System.getProperty();参数
  19. PL/SQL编程1-基础
  20. C 标准库 - string.h之memcmp使用

热门文章

  1. 如何构建 Redis 高可用架构?
  2. 高性能网络编程(一):单台服务器并发TCP连接数到底可以有多少
  3. 用Riffstation扒带
  4. 启动MyEclipse8.5时未响应
  5. 图解MySQL 内连接、外连接
  6. 转---一文读懂 python 的元类
  7. kombu源码Producer收获一
  8. PHP 设计模式 单例模式 工厂模式 注册模式
  9. js简单的面试题
  10. html中的body和head有什么区别??