jq链式调用实现demo

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43414945/article/details/102532149

jq链式调用的实现方法

最近回顾一下设计模式的方法,这里简单实现jq的链式条用方法,代码不算原创,但是个人也算是复习巩固加深理解,特别是加深对js原型链的理解,废话不多说直接上代码。

<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
</head>
<body>
 <div id="box" style="width:200px; height:200px; color:red; background:blue;">我是一个大笨象</div>
 <script>

     //封装一个函数实现jq的链式调用
     (function(window ,undefined){
         // 传入window 是为了再函数内部提高 寻找全局变量的window速度 方便将内部
         //的方法暴露给全局
         // 传入undefined 是为了防止低版本的id篡改undefined的值
         // 以 _开头,一般约定好都是私有的
         //再这里首先定义一个私有的构造函数
         function _$(args){
             var id = args[0].substring(1)// 获取id选择符的id值
             this.dom = document.getElementById(id);//将获取的dom挂载再实例上
         }
       //再私有的构造函数上添加各种方法
       //注意 这里由于重写了原型对象 所有要将原型对象的constructor属性重新指向 私有的构造函数
       _$.prototype = {
             constructor: _$,
         //添加方法 
         // 实现jq的html方法
         html: function () {
             //如果传参数,说明想获取内容
             if(arguments.length === 0){
                 return this.dom.innerHTML;
             }
             //如果传参数说明是想设置内容
             if(arguments.length == 1){
                 this.dom.innerHTML = arguments[0];
                 return this;//为了实现链式调用 返回实例对象
             }

         },
         //实现jq的css方法
         css: function () {
            if(arguments.length === 0){
                //如果不传参数则抛出错误
             throw new Error('css方法要求参数是必传')
            }
            if(arguments.length === 1){
                //参数为一个时 表示获取对应的样式
                return this.dom.style[arguments[0]];
            }
            if(arguments.length === 2){
                //参数为两个时 表示设置对应的样式
                this.dom.style[arguments[0]] = arguments[1];
                return this;//放回实例对象 方便链式调用
            }
         }

       }
     //通过window将这个私有的方法暴露给全局,再全局则可以使用 这个对象的所有功能
     window.$ = function(){
         //返回私有构造函数的实例 将函数参数对象arguments传给私有的构造函数
         return new _$(arguments);
     }

     })(window)

  var psy = $('#box').html();
  console.log(psy);
  var setpsy = $('#box').html('我是一只小小鸟').css('height','800px');
     
 </script>
</body>
</html>

如又错误 还望指出

猜你喜欢

转载自blog.csdn.net/weixin_43414945/article/details/102532149