JavaScript实现链式调用

本文介绍了如何使用JavaScript实现链式调用,包括通过构造函数返回this实现DOM操作的链式调用,以及给Number对象原型添加方法实现数值运算的链式调用。

学习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) //28

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

 

转载于:https://www.cnblogs.com/camille666/p/js_chain_call.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值