jQuery原理——编写自己的jQuery框架

一:编写自己的jQuery框架

根据官方的结构编写自己的jQuery

(function (window, undefined) {
     var sjQuery = function () {
         return new sjQuery.prototype.init();
     }
     sjQuery.prototype = {
         constructor: sjQuery
     }
     sjQuery.prototype.init.prototype = sjQuery.prototype;
     window.sjQuery = window.$ = sjQuery;
 })(window);

二:编写jQuery入口函数

根据文章jQuery——20——jQuery的基本结构和入口函数测试中的入口函数测试部分来编写自己的jQuery入口函数
1.传入’’ null undefined NaN 0 false,返回空的jQuery对象

html:

<!DOCTYPE html>
<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>
  <script src="../jQuery/sjQuery.js"></script>/*引入自己的jquery*/
  <script>
    console.log($());
    console.log($(''));
    console.log($(null));
    console.log($(undefined));
    console.log($(NaN))
    console.log($(0))
    console.log($(false))
  </script>

</head>

<body>

</body>

</html>   

sjQuery.js:

 (function (window, undefined) {
     var sjQuery = function (selector) {
         return new sjQuery.prototype.init(selector);
     }
     sjQuery.prototype = {
         constructor: sjQuery,

         init: function (selector) {
             //1.传入'' null undefined NaN 0 false,返回空的jQuery对象
             if (!selector) {
                 return this;
             }
         }
     }
     sjQuery.prototype.init.prototype = sjQuery.prototype;
     window.sjQuery = window.$ = sjQuery;
 })(window);


2.字符串:
2.1代码片段:会将创建好的DOM元素存储到jQuery对象中返回
html: console.log($('<p>1</p><p>2</p><p>3</p>'));

sjQuery.js:

  (function (window, undefined) {
     var sjQuery = function (selector) {
         return new sjQuery.prototype.init(selector);
     }
     sjQuery.prototype = {
         constructor: sjQuery,

         init: function (selector) {
             //1.传入'' null undefined NaN 0 false,返回空的jQuery对象
             if (!selector) {
                 return this;
             }
             //2.字符串
             else if(typeof selector==='string'){
                 //2.1判断是否是代码片段<a>
                 if(selector.charAt(0)=="<"&&selector.charAt(selector.length-1)==">"&&selector.length>=3){
                    //console.log('代码片段');
                    //1.根据代码片段创建所有的元素
                    var temp=document.createElement('div');
                    temp.innerHTML=selector;
                    // console.log(temp);
                    //2.将创建好的一级元素添加到jQuery当中
                //   console.log(temp.children);//children方法
                for(var i=0;i<temp.children.length;i++){
                    this[i]=temp.children[i];
                }
                    //3.给jQuery对象添加length属性
                    this.length=temp.children.length;
                    //4.返回加工好的this(jQuery)
                    return this;
                 }
                 //2.2判断是否是选择器

             }
         }
     }
     sjQuery.prototype.init.prototype = sjQuery.prototype;
     window.sjQuery = window.$ = sjQuery;
 })(window);

封装方法后:
sjQuery.js:

 (function (window, undefined) {
     var sjQuery = function (selector) {
         return new sjQuery.prototype.init(selector);
     }
     sjQuery.prototype = {
         constructor: sjQuery,

         init: function (selector) {
             //1.传入'' null undefined NaN 0 false,返回空的jQuery对象
             if (!selector) {
                 return this;
             }
             //2.字符串
             else if(sjQuery.isString(selector)){
                 //2.1判断是否是代码片段<a>
                 if(sjQuery.isHTML(selector)){
                    //console.log('代码片段');
                    //1.根据代码片段创建所有的元素
                    var temp=document.createElement('div');
                    temp.innerHTML=selector;
                    // console.log(temp);
                    //2.将创建好的一级元素添加到jQuery当中
                //   console.log(temp.children);//children方法
                for(var i=0;i<temp.children.length;i++){
                    this[i]=temp.children[i];
                }
                    //3.给jQuery对象添加length属性
                    this.length=temp.children.length;
                    //4.返回加工好的this(jQuery)
                    return this;
                 }
                 //2.2判断是否是选择器

             }
         }
     }
     sjQuery.isString=function(str){
         return typeof str==="string"
     }
     sjQuery.isHTML=function(str){
         return str.charAt(0)=="<"&&str.charAt(str.length-1)==">"&&str.length>=3
     }
     sjQuery.prototype.init.prototype = sjQuery.prototype;
     window.sjQuery = window.$ = sjQuery;
 })(window);

我们发现,如果字符串有空格识别不出来 console.log($(' <div><p>1</p></div><div><p>2</p></div> '))
改进后的代码

 (function (window, undefined) {
     var sjQuery = function (selector) {
         return new sjQuery.prototype.init(selector);
     }
     sjQuery.prototype = {
         constructor: sjQuery,
         init: function (selector) {
             //0.去除字符串两边的空格 
             selector = sjQuery.trim(selector);
             //1.传入'' null undefined NaN 0 false,返回空的jQuery对象
             if (!selector) {
                 return this;
             }
             //2.字符串
             else if (sjQuery.isString(selector)) {
                 //2.1判断是否是代码片段<a>
                 if (sjQuery.isHTML(selector)) {
                     //console.log('代码片段');
                     //1.根据代码片段创建所有的元素
                     var temp = document.createElement('div');
                     temp.innerHTML = selector;
                     // console.log(temp);
                     //2.将创建好的一级元素添加到jQuery当中
                     //   console.log(temp.children);//children方法
                    //  for (var i = 0; i < temp.children.length; i++) {
                    //      this[i] = temp.children[i];
                    //  }
                     //3.给jQuery对象添加length属性
                   
                     //简化第2,3步
                     [].push.apply(this,temp.children);
                     //此时此刻的this是sjQuery对象
                     //4.返回加工好的this(jQuery)
                     return this;
                 }
                 //2.2判断是否是选择器

             }
         }
     }
     sjQuery.isString = function (str) {
         return typeof str === "string"
     }
     sjQuery.isHTML = function (str) {
         return str.charAt(0) == "<" && str.charAt(str.length - 1) == ">" && str.length >= 3
     }
     sjQuery.trim = function (str) {
         //判断是否支持trim方法
         if (str.trim) {
             return str.trim();
         } else {
             return str.replace(/^\s+|\s+$/g, ''); //用空串代替空格字符串
         }
     }

     sjQuery.prototype.init.prototype = sjQuery.prototype;
     window.sjQuery = window.$ = sjQuery;
 })(window);

2.2选择器:会将找到的所有元素存储到jQuery对象中返回
注意:要将window.onload打开,不然为空

3.数组: 会将数组中存储的元素依次存储到jQuery对象中返回

4:除上述类型以外的: 会将传入的数据存储到jQuery对象中返回

判断是否为函数类型

函数类型会返回“function”函数类型会返回“function”

全部代码:sjQuery.js

 (function (window, undefined) {
     var sjQuery = function (selector) {
         return new sjQuery.prototype.init(selector);
     }
     sjQuery.prototype = { //原型
         constructor: sjQuery,
         init: function (selector) {
             //0.去除字符串两边的空格 
             selector = sjQuery.trim(selector);
             //1.传入'' null undefined NaN 0 false,返回空的jQuery对象
             if (!selector) {
                 return this;
             } else if (sjQuery.insFuntion(selector)) {
                 // console.log('是方法');
                 sjQuery.ready(selector); //把传递进来的回调函数传递给ready方法

             }
             //2.字符串
             else if (sjQuery.isString(selector)) {
                 //2.1判断是否是代码片段<a>
                 if (sjQuery.isHTML(selector)) {
                     //console.log('代码片段');
                     //1.根据代码片段创建所有的元素
                     var temp = document.createElement('div');
                     temp.innerHTML = selector;
                     // console.log(temp);
                     //2.将创建好的一级元素添加到jQuery当中
                     //   console.log(temp.children);//children方法
                     //  for (var i = 0; i < temp.children.length; i++) {
                     //      this[i] = temp.children[i];
                     //  }
                     //3.给jQuery对象添加length属性

                     //简化第2,3步
                     [].push.apply(this, temp.children);
                     //4.返回加工好的this(jQuery)
                     //  return this;
                 }
                 //2.2判断是否是选择器
                 else {

                     // 1.根据传入的选择器找到对应的元素
                     var res = document.querySelectorAll(selector);
                     // 2.将找到的元素添加到sjQuery上
                     [].push.apply(this, res);
                     // 3.返回加工上的this
                     //  return this;
                 }


             } //3.数组
             //   else if(typeof selector==='object'&&'length' in selector&&selector!==window){//window也是对象,并且length=0
             /*
           //3.1真数组
           if(({}).toString.apply(selector)==="[object Array]"){
            //   console.log('真数组');
            //真数组转换为伪数组
            [].push.apply(this,selector);
            // return this;
               
           }
           //3.2伪数组
           else{
        //    console.log('伪数组');
        //企业开发中,要将自定义伪数组转换为伪数组,首先将它转换为真数组
        //因为IE8及以下不能直接将自定义的伪数组包装成伪数组返回
        //将自定义的伪数组转换为真数组
        var arr=[].slice.call(selector);
        //将真数组转换为伪数组
        [].push.apply(this,arr);
        return this;
        
           }
           */
             //简化以上代码
             //将自定义的伪数组转换为真数组
             else if (sjQuery.isArray(selector)) {
                 var arr = [].slice.call(selector);
                 //将真数组转换为伪数组
                 [].push.apply(this, arr);
                 //   return this;
             }
             //除上述类型以外
             else {
                 this[0] = selector; //将其保存到jQuery
                 this.length = 1;
                 //  return this;
             }
             return this;
         },
         jQuery: "3.4.1", //模拟版本号
         selector: "", //默认为空
         length: 0,

         //[].push找到数组的push方法
         //冒号前面的push将由sjQuery对象调用

         //相当于[].push.apply(this);,把push内部的this替换成sjQUery对象
         push: [].push,
         sort: [].sort,
         splice: [].splice,
         toArray: function () {
             return [].slice.call(this);
         },
         get:function(num){
         //没有传递参数
         if(arguments.length===0){
             return this.toArray();
         }
         //传递参数,参数不是负数
         else if(num>=0){
             return this[num];
         }
         //传递负数
         else {
              return this[this.length+num];
         }
         },
         eq: function (num) {
            // 没有传递参数
            if(arguments.length === 0){
                return new sjQuery();
            }else{
                return sjQuery(this.get(num));
            }
        },
        first:function(num){
            return this.eq(0);
        },
        last:function(num){
            return this.eq(-1);
        },
        each:function(fn){
            return sjQuery.each(this,fn);
        },
        map:function(obj,fn){
            
        }

     }
     sjQuery.extend = sjQuery.prototype.extend = function (obj) {
         for (var key in obj) {
             this[key] = obj[key];
         }
     }
     sjQuery.extend({ //key/value
         isString: function (str) {
             return typeof str === "string"
         },
         isHTML: function (str) {
             return str.charAt(0) == "<" && str.charAt(str.length - 1) == ">" && str.length >= 3
         },
         trim: function (str) {
             //如果不是字符串,则不用去除空格
             if (!sjQuery.isString(str)) {
                 return str;
             }
             //判断是否支持trim方法
             if (str.trim) {
                 return str.trim();
             } else {
                 return str.replace(/^\s+|\s+$/g, ''); //用空串代替空格字符串
             }
         },
         isObject: function (sele) {
             return typeof sele === "object"
         },
         isWindow: function (sele) {
             return sele === window;
         },
         isArray: function (sele) {
             if (sjQuery.isObject(sele) &&
                 !sjQuery.isWindow(sele) &&
                 "length" in sele) {
                 return true;
             }
             return false;
         },
         insFuntion: function (sele) {
             return typeof sele === 'function';
         },
         ready: function (fn) { //当传入的是方法函数类型,当判断页面的DOM元素加载完后开始执行代码,比如body里有div,若没有等dom加载完就执行代码,会找不到div
             //判断DOM是否加载完毕
             if (document.readyState == "complete") {
                 fn(); //直接回调
             } else if (document.addEventListener) { //如果浏览器兼容此方法
                 document.addEventListener('DOMContentLoaded', function () {
                     fn();
                 })
             } else {
                 document.attachEvent('onreadystatechange', function () { //attachEvent不兼容火狐谷歌
                     if (document.readyState == "complete") {
                         fn();
                     }
                 })
             }

         },
         each: function (obj, fn) {
            // 1.判断是否是数组
            if(sjQuery.isArray(obj)){
                for(var i = 0; i < obj.length; i++){
                   // var res = fn(i, obj[i]);
                   var res = fn.call(obj[i], i, obj[i]);
                   if(res === true){
                       continue;
                   }else if(res === false){
                       break;
                   }
                }
            }
            // 2.判断是否是对象
            else if(sjQuery.isObject(obj)){
                for(var key in obj){
                    // var res = fn(key, obj[key]);
                    var res = fn.call(obj[key], key, obj[key]);
                    if(res === true){
                        continue;
                    }else if(res === false){
                        break;
                    }
                }
            }
            return obj;
        },
        map: function (obj, fn) {
            var res = [];
            // 1.判断是否是数组
            if(sjQuery.isArray(obj)){
                for(var i = 0; i < obj.length; i++){
                    var temp = fn(obj[i], i);
                    if(temp){
                        res.push(temp);
                    }
                }
            }
            // 2.判断是否是对象
            else if(sjQuery.isObject(obj)){
                for(var key in obj){
                    var temp =fn(obj[key], key);
                    if(temp){
                        res.push(temp);
                    }
                }
            }
            return res;
        }
     });

     sjQuery.prototype.init.prototype = sjQuery.prototype;
     window.sjQuery = window.$ = sjQuery;
 })(window);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值