实现jQuery底层链式编程(二)

//jquery使用的就是块级作用域

      //特点1.块级作用域的作用就是程序启动时,直接执行了
      //特点2.内部的成员变量,外部无法访问

      (function(Window,undefined){
        // $ 最常用的对象,返回给外界,等于出口,一般大型程序当中 _ 作为私有对象(规范)
        function _$(arguments){
          //实现代码....
          //正则表达式,匹配ID
          var idselector = /#\w+/;

          //此属性接受所得到的元素
          this.dom;

          if(idselector.test(arguments[0])){
            //如果匹配则成功,则接受dom元素
            this.dom = document.getElementById(arguments[0].substring(1));
          }else{
            throw new Error('arguments it error');
          }
        }

        //在Function类上扩展一个可以实现链式变成的方法
        //参数1:链式方法的名字
        //参数2:函数
        Function.prototype.method = function(methodName,fn){
          //_$原型
          this.prototype[methodName] = fn;
          //链式变成的关键
          return this;
        }

        //在_$上通过原型,增加公共的方法
        _$.prototype = {
          constructor : _$,
          addEvent : function(type,fn){
            //console.log('addEvent');
            //给得到的元素添加事件
            if(window.addEventListener){
              this.dom.addEventListener(type,fn);
            }else if(window.attachEvent){
              this.dom.attachEvent('on'+type,fn);
            }
            return this;
          },
          colorStyle : function(key,value){
            //console.log('colorStyle');
            this.dom.style[key] = value;
            return this;
          }
        }

        //window上先注册一个全局变量,与外界产生联系,外界可以访问
        window.$ = _$;

        //写一个准备方法,在_$绑定一个方法
        _$.onReady = function(fn){
          //1.实例化出来_$对象,真正的注册到window上
          window.$ = function(){
            return new _$(arguments);
          };

          //2.执行传入进来的代码,onReady函数里传入的
          fn();

          //3.实现链式编程
          _$.method('addEvent',function(){

          }).method('colorStyle',function(){

          });
        }

      })(window);//window等于程序的入口,传入作用域中

      //运行
      $.onReady(function(){
        var inp = $('#input');
        //var domObject = inp.get(0);
        //console.log(inp.dom);
        //alert(inp.dom);
        inp.addEvent('click',function(){
          console.log('我执行了');
        }).colorStyle('backgroundColor','#ff6699');
      });

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值