jQuery-day02

The Write Less,Do More

  • 对象构造
  1. 要解决无new,拿么只能在函数里边new,但是new自己容易出现无限递归自己。那么就要想办法,不能new 自己,那能不能new别人,然后让这个人拥有和自己一样的属性和方法,只是换了个名字而已,当然是可以的。如是就有了new ajQuery.fn.init( selector ). 在init()方法里返回this,然后将init.prototype=ajQuery.prototype,这样,init()返回的this 就拥有了ajQuery所有的属性和方法。绕了一个圈,目的就为了不new自己也能得到和自己拥有相同属性和方法的实例对象。
// jQuery的写法(为了减少new 产生this 于是jq很巧妙的利用了jQuery.fn.init方法进行了间接实例化)
var jQuery = function(selector, context) {
  return new jQuery.fn.init(selector, context);
}
// init.prototype = jQuery.fn;
init=jQuery.fn.init = jQuery.fn = jQuery.prototype = {
  init: function() {
    this.name = 'aaron'
    return this; //这个this是指向jQuery.fn
  },
  constructor: jQuery
}

  • jQuery采用了实例方法跟静态方法共享的设计思想;
  1. each 方法
    $(".aaron").each()   //作为实例方法存在
    $.each()             //作为静态方法存在
  1. 源码
    jQuery.prototype = {
    each: function( callback, args ) {
        return jQuery.each( this, callback, args );
    }
}
  1. 分析
    1. 在$()时,并没使用jQuery构造,而仅调用了jQuery函数,在jQuery函数内部通过new构造了init函数的实例(js中每一个函数都有一个原型prototype),那返回的新对象都是init构造的实例,它们都可访问init.prototype,而jQuery所有的方法都写在jQuery的jQuery.prototype上,要使实例能访问到jQuery上的方法,用继承或复制的方式将jQuery.prototype对象上的方法挂载到init.prototype上即可(因init.prototype一个方法也没写,所以可直接jQuery.prototype赋给init.prototype)
  • 链式调用
    aQuery().init().name()
  1. return this返回该实例
posted @ 2020-03-08 22:40  Devin_n  阅读(79)  评论(0编辑  收藏  举报