jquery 那些事儿~

var $$ = ajQuery = function(selector) {
    return new ajQuery.fn.init(selector);
}

ajQuery.fn = ajQuery.prototype = {
    name: 'aaron',
    init: function(selector) {
        this.selector = selector;
        return this;
    },
    constructor: ajQuery
}

/******************2个构造器关联的关键****************************/
ajQuery.fn.init.prototype = ajQuery.fn;


ajQuery.fn.say = function() {
    $("#aaron").html(this.name);
}

$$().say()

/******************jquery extend 插件接口设计****************************/
ajQuery.extend = ajQuery.fn.extend = function() {
    var options, src, copy,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length;

    //只有一个参数,就是对jQuery自身的扩展处理
    //extend,fn.extend
    if (i === length) {
        target = this; //调用的上下文对象jQuery/或者实例
        i--;
    }
    for(; i < length; i++){
        //从i开始取参数,不为空开始遍历
        if((options = arguments[i]) != null){
            for(name in options){
                copy = options[name];
                //覆盖拷贝
                target[name] = copy;
            }
        }
    }
    return target;
}

//jQuery 静态方法接口
jQuery.extend({
   Deferred:function(func){
        ...省略代码....
        return deferred
   },
   when:function(func){
      ...省略代码....
      return deferred.promise();
   }
})

//jQuery 实例方法接口
ajQuery.fn.extend({
    setName: function(myName) {
        this.myName = myName
        return this;
    },
    getName: function() {
        $("#aaron").html(this.myName)
        return this;
    }
});

$$().setName('demo').getName();
console.log('讲解一下上面的代码:因为extend的核心功能就是通过扩展收集功能(类似于mix混入),所以就会存在收集对象(target)与被收集的数据,因为jQuery.extend并没有明确实参,而且是通过arguments来判断的,所以这样处理起来很灵活。arguments通过判断传递参数的数量可以实现函数重载。其中最重要的一段target = this,通过调用的方式我们就能确实当前的this的指向,所以这时候就能确定target了。最后就很简单了,通过for循环遍历把数据附加到这个target上了。当然在这个附加的过程中我们还可以做数据过滤、深拷贝等一系列的操作了。');
 
原文地址:https://www.cnblogs.com/oceanden/p/4326631.html