Fork me on GitHub

李可

导航

jQuery中的几个模块总结

Query插件,以备并希望在前端方面有所长进。请批评指正。

一,类型判断全解

JQuery判断类型扩展方法:$.type()

1 /*type: function( obj ) {
2             if ( obj == null ) {
3                 return obj + "";
4             }            
5             return typeof obj === "object" || typeof obj === "function" ?
6                 class2type[ toString.call(obj) ] || "object" :
7                 typeof obj;
8         }*/
$.type()

本质:就是运用{}.toString.call()或者(Object.prototype.toString.call())。

自己模仿写出来一个方法:

1 function getType(o) {
2             var _target;
3             return (
4                 (_target = typeof (o)) == "object" ? Object.prototype.toString.call(o).slice(8, -1) : _target)
5                 .toLowerCase();
6         }
getType

但这个方法只是判断继承Object复杂类型下的Date Array RegExp等typeof判断不出的子类型。

1,typeof 2,instanceof 3,constructor 4,{}.toString.call()或者(Object.prototype.toString.call())

Boolean Number String Function Array Date RegExp Object Error Null Undefined

 1         //1,数据类型:5种简单基本类型:Undefined Boolean String Number Null 1种复杂类型Object
 2         //2,但根据返回值得到的类型有6种,“undefined” “boolean” “string” “number” “function” “object”。注意将Null去掉,换成“function”。都以小写字母开头
 3         //比如操作符操作字符串会返回上面6种,注意一点:将typeof null会返回“object”,注意返回object的表示这个值是对象(包括Array)或者null,
 4         //1Array Date返回object 2Math 数字返回number 3字符串new返回object 直接定义返回object
 5         var arr1 = [1, 2, 3];
 6         var arr2 = new Array()
 7         var dat = new Date();
 8         var mat1 = Math.PI;
 9         var mat2 = Math.random();
10         alert(typeof arr1);//object
11         alert(typeof arr2);//object
12         alert(typeof dat);//object
13         alert(typeof mat1);//number
14         alert(typeof mat2);//number
15 
16         alert(typeof [])//object
17         alert(typeof null);//object
18         //字符串有点特殊
19         var s1 = 'abc';
20         var s2 = new String('def');
21         alert(typeof s1);//string
22         alert(typeof s2);//object
23 
24         function fun() {
25 
26         }
27         alert(typeof fun);//function  
28         //3,一般null==undefined返回true ,null===undefined 返回false
29         if (null == undefined) { alert(true) }//true
30         if (null === undefined) { alert(true) } else {
31             alert(false);
32         }
33         //4,Boolean 转换成false的的类型 “” 0和NaN null undefined 
typeof
 1   //instance
 2         var a = "abc.";
 3         var b = 1;
 4         var c = [1, 2, 3];
 5         var d = new Date();
 6         var e = function () { alert(1); };
 7         var f = function () { this.name = "2"; };        
 8         alert(c instanceof Array) //true
 9         alert(d instanceof Date) 
10         alert(f instanceof Function)//true
11         // alert(f instanceof function)// false
12         //instanceof 后面一定要是对象类型,注意大小写不能错
instanceof
1  function A() { }
2         alert(typeof A);//function
3         var a = new A();
4         alert(typeof a);//object
5 
6         //构造函数 
7         //new 1创建实例 2将函数的原型赋值给这个实例 3执行这个函数 并且这个函数的上下文this就是这个实例
8         alert(a.constructor)// function A() { }
9         alert(a.constructor === A)//true  ***************注意实例能直接调用对应原型中属性方法。比如a直接调用原型中的constructor
constructor
1 function A() { }
2         var a = new A();
3         alert({}.toString.call(a))//[object Object]
4         alert({}.toString.call(A))//[object Function]
5         alert(Object.prototype.toString.call([]))//[object Array]
6         alert({}.toString.call([]))//[object Array]
7         alert({}.toString.call(new Date()))//[Object Date]
{}.toString.call()或者(Object.prototype.toString.call())

/1typeof:判断除了Null的5个基本类型准确,但是想Date Array Regexp不准 2先知道类型,再判断是否是这个类型
//instaneceof,准确,但必须先知道类型,然后判断是否为这个类型
//constructor(得到构造函数
//跨iframe时候 instanceof 和constructor有问题,具体什么问题不清楚
//用jquery.type(),把null undefined 复杂类型和 除null和undefined外的4中基本类型都包含了。 核心代码{}.toString.call(obj) //[object ...]

二,创建对象全解

jQuery创建$(),这$()是个方法,里面renturn一个对象,new的时候,覆盖构造函数的对象。运用构造函数+寄生创建对象,核心理解原型链。

 1 var jQuery = function( selector, context ) {
 2         // The jQuery object is actually just the init constructor 'enhanced'
 3         return new jQuery.fn.init( selector, context );
 4     }
 5 
 6 jQuery.fn = jQuery.prototype = {
 7     init: function( selector, context ) {
 8         var match, elem, ret, doc;
 9 
10         // Handle $(""), $(null), or $(undefined)
11         if ( !selector ) {
12             return this;
13         }
14 .......
15 
16 jQuery.fn.init.prototype = jQuery.fn;
$()对象创建

return new jQuery.fn.init( selector, context );为什么不直接返回new jQuery();应为new的时候,会调用jQuery....然后又new..死循环。
将jquery下的prototype下的init方法的原型=jquery下的prototype。意思:newjQuery.fn.init()对象具有 init方法的原型中的所有方法 的实例,就会具有jquery下的prototype下的所有方法,扩展jquery下的prototype下的方法。就等于扩展$()的方法。

创建对象的形式:说的3种,5种什么的,没什么意思的。其实看书之后总结是7种,不过没什么意思。核心还是构造函数+原型,知道之后其余的稍微看一下就会的。

原始:var obj={};或者var obj=new Object() ;obj.attr1=..,obj.attr2=..

工厂:function factory(par1,par2,...){var obj=new Object();obj.attr=par1..;return obj}

构造函数:function A(){} var a=new A();

构造函数+原型:function A(){} var a=new A(); A.prototype={attr1:..;fun1:...}

动态构造函数:function A(){this.attr1=..;this.attr2=..;if(typeof this.fun1!='function'){A.prototype.fun1=function(){....}}}    var a=new A(); a.fun1();//函数内部没有的,我再在原型中创建。这个整体写法,将原型写到方法体内了。就相当我们c#的语言一样了,将类的所有的方法写到一个类中。

寄生构造函数:function A(){vat a=new ..;this.attr1=...   return a;}//return的结果,覆盖构造函数new时候默认返回的实例。

稳妥构造函数:看高级编程之后,实在发现不出和工厂方法有什么区别。这都什么飞机?我简单认为就是工厂模式。核心为了“安全”,不使用this,不使用new。

三,引用问题

//在h5游戏开发中,经常会有这样的要求:复制出一个对象,但修改原来的对象,不会造成对复制出的对象造成影响。我们需要理解一些基本的东西。

 1         //1在闭包内,尽量不适用同一个变量名,比如下面的a。因为作用域就近找变量。不会按照人眼看到的从上到下执行。
 2         //2变量和函数的声明,放到最上面。因为js程序运行的时候自动会将声明提升到当前作用域的最顶端
 3         var a = "global";
 4         function b() {
 5             console.log(a);//undefined  1先在当前上下文作用域内找a,就近原则!。当前作用于内不存在,就从上级作用域找...上级
 6             var a = "local";//此时var a声明会提升到当前上下文(作用域最顶端)
 7             console.log(a);//local
 8         }
 9         b();
10 
11         var m = "global";
12         function n() {
13             var m;
14             console.log(m);//undefined
15             m = "local";
16             console.log(m);//local
17         }
18         n();
19         var k = "global";
20         function l() {
21             var k;
22             console.log(k);//undefined  找到当前作用域的k,就不会再往作用域链上继续找
23             console.log(k);//undefined
24         }
25         l();
26         var s = "global";
27         function t() {
28             console.log(s);//undefined  找到当前作用域的k,就不会再往作用域链上继续找
29             console.log(s);//undefined
30         }
31         t();
变量,函数声明的习惯。常出现的错误

四,扩展实质全解

jQuery.extend = jQuery.fn.extend = function() {
    // copy reference to target object
    var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;
        target = arguments[1] || {};
        // skip the boolean and the target
        i = 2;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // extend jQuery itself if only one argument is passed
    if ( length === i ) {
        target = this;
        --i;
    }

    for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // Recurse if we're merging object literal values or arrays
                if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
                    var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
                        : jQuery.isArray(copy) ? [] : {};

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};
jQuery的扩展(extend)

注意:$.extend和$().extend,都是用这一个方法搞定的。

1  //extend
2         var obj1 = $.extend({}, { name: 'lk', age: 18 }, { weight: 120 })
3         var obj2 = $.extend({}, { name: 'lk', attr: { age: 15, hair: 'red' } }, { weight: 120 })
4         var obj3 = $.extend(false, { name: 'lk', attr: { age: 15, hair: 'red' } }, { weight: 120 }, { attr: { sight: 5.0 } })
5         console.log(obj3);//{name: "lk",weight: 120,attr:{sight: 5.0}}
6         var obj4 = $.extend(true, { name: 'lk', attr: { age: 15, hair: 'red' } }, { weight: 120 }, { attr: { age: 18, sight: 5.0 } })
7         console.log(obj4);//{name: "lk",weight: 120,attr:{age: 18, hair: 'red',sight: 5.0}}
extend使用

注意递归的使用:

  function multi(num) {
            //终止条件
            if (num == 1) {
                return 1;
            }

            return num * multi(num - 1);//5*4*3*2*1

        }
        console.log(multi(5))//120
递归,先递后归

//我们想把这个对象真正的复制一份出来
var obj1 = { a: 15 }
var obj2 = obj1;
obj1.a = 18;
console.log(obj2); //{a:18 }//想要的是讲obj1对象“拷贝”给obj2之后,改obj1,不会造成对obj2的影响。

拷贝就是采用的递归:

 1  function copy(obj) {
 2             var newObj = {}
 3 
 4             for (var key in obj) {
 5                 newObj[key] = obj[key]
 6             }
 7             return newObj;
 8 
 9         }
10         var obj4 = copy(obj3);
11         obj3.a = 18;
12         console.log(obj3)//{a:18}
13         console.log(obj4)//{a:20} 通过这种拷贝的形式,就会使得不会相互影响,脱离的“引用问题”干扰。
模拟一个浅拷贝
function deepCopy(obj) {
            //终止条件,当不是{key:value}对象时
            if (typeof obj != 'object') {
                return obj;
            }
            var newObj = {}
            for (var key in obj) {
                newObj[key] = deepCopy(obj[key]);//“递”次调用,最后”归“一

            }
            return newObj;

        }
        var obj8 = deepCopy(obj7);
        obj7.a.b.c = 18;
        console.log(obj7);//{ a: { b: { c: 18 } } }
        console.log(obj8); //{ a: { b: { c: 15 } } }
模拟一个深拷贝

自己模仿一个扩展。

 1   function Bird() {
 2             this.wing = 2;
 3             this.fly = function () {
 4                 alert("fly");
 5             }
 6         }
 7  Bird.kuozhan = Bird.prototype.kuozhan = function (obj) {
 8             for (var key in obj) {//{a:5,b:10}
 9                 this[key] = obj[key]
10             }
11             return this;
12         }
Bird.kuozhan=Bird.prototype.kuozhan =function(){}
 1   //函数:既是方法,又是变量,还是对象。那么函数肯定有属性、方法
 2         //扩展静态方法
 3         //var Bird= function () {
 4 
 5         function Bird() {
 6             this.wing = 2;
 7             this.fly = function () {
 8                 alert("fly");
 9             }
10         }
11         Bird.say = function () {
12             alert('say');
13         }
14         Bird.run = function () {
15             alert('run');
16         }
17         // Bird.fly();//这里出现错误,只能其实例调用
18         var bird = new Bird();
19         bird.fly();
20 
21         Bird.say();//say
22         Bird.run();//run
23         //对一个方法对象扩展同时扩展多个方法(自己调用),更为方便的写法
24         //看一些框架中,把扩展的多个方法弄成一个对象,整体做参数,传进去,就把这个参数对象的方法一个一个扩展到原来对象上去了。就类似
25         //{fun1:function(){},fun2:function(){},fun3:function(){}},然后一自动对齐,显得逼格十足。
26         //要实现这点,下部如何将一个对象的方法一个一个扩展到原来对象上去呢?是的,我们就写出这个扩展方法。少用“=”,多用“:”
27 
28         Bird.kuozhan = Bird.prototype.kuozhan = function (obj) {
29             for (var key in obj) {//{a:5,b:10}
30                 this[key] = obj[key]
31             }
32             return this;
33         }
34         Bird.kuozhan({
35             s: function () {
36                 alert('1');
37             },
38             r: function () {
39                 alert('2');
40             }
41         })
42         Bird.s();
43         Bird.r();
44         Bird.prototype.kuozhan({
45             m: function () {
46                 alert('m');
47             },
48             n: function () {
49                 alert('n');
50             }
51         })
52         var b = new Bird();
扩展使用

五,继承注意

 

 1 /*引用的问题*/
 2         /*********************************************************************/
 3         /*数组*/
 4         var a=[1,2,3];
 5         var b=a;
 6         //a.push(4);//修改的问题
 7         b.push(4);//修改的问题
 8         console.log(a);//[1,2,3,4]
 9         console.log(b);//[1,2,3,4]
10 
11 
12         var a=[1,2,3];
13         var b=a;
14         //=等号 :重开辟新空间重新赋值 开辟新空间导致  就不会再存在引用类型修改的问题
15         a=[7,8,9]
16         console.log(a);//[7,8,9]
17         console.log(b);//[1,2,3,4]
18 
19         /*********************************************************************/
20          /*object*/
21          var obj1={name:"老李"};
22          var obj2=obj1;
23          obj2.name="老王"
24          console.log(obj1);//{name:"老王"}
25          console.log(obj2);//{name:"老王"}
26 
27          var obj1={name:"老李"};
28          var obj2=obj1;
29 
30          obj2={haha:"笑哈哈"}
31          console.log(obj1);{name:"老李"}
32          console.log(obj2);{haha:"笑哈哈"}
33 
34         /*********************************************************************/
35         /*特殊的方法,不能修改*/
36         var a=function(){alert('qqqqq')}
37         var b=a;
38         //函数只能=  函数不能修改,不存在修改的问题 
39         b=function(){alert('wwww')}
40         a();//qqqqq
41         b();//wwww
数组、Object、function,修改、重新赋值的问题

 

 

 

 

 

 function Person(name, age) {
            this.name = name;
            this.age = age;
            this.aler = function () {
                alert(1);
            }
        }
        Person.prototype = {//因为prototype是对象,可以写成无序键值对
            sayHi: function () { alert('sayhi'); },
            sayHello: function () { alert('sayhello'); }
        }
        function student(sname, sage) {//
            Person.call(this, sname, sage);//we
        }
        //student.prototype = Person.prototype;
        student.prototype = new Person();
        student.prototype.constructor = student;

        var stu1 = new student();
        stu1.aler();
        stu1.sayHi();
        stu1.sayHello();
继承勿忘修正构造函数指向

//student.prototype = Person.prototype;
student.prototype = new Person();//可以来个”父类“实例,因为原型链
student.prototype.constructor = student;//上面的代码已经破坏了原型的构造指向,勿忘修改。

posted on 2015-09-08 15:08  李可在江湖  阅读(2712)  评论(2编辑  收藏  举报