jquery源码'jQuery.fn.init.prototype'

一般我们在创建构造函数即使用的时候会这样写,使用的时候会使用new 关键字,先实例化,然后使用。

    function test(name, age) {
        this.name = name;
        this.age = age;
        this.sayHello = function(){
            console.log(this.name+ ', say hello');
        }
    }
    var ls = new test('ls',23);
    ls.sayHello();

然而在使用jquery 的时候 都是直接使用其方法,不需要使用new 关键字。

看了下jquery源码,在jquery 有这样一段代码:

var jQuery = function( selector, context ) {
    return new jQuery.fn.init( selector, context, rootjQuery );
}

在这段代码中,jQuery()方法返回了 jQuery.fn.init() 的构造方法的实例化对象。

所以我们可以在使用 jQuery 方法的时候 ,可以直接使用其公有方法,例如 text(),不需要new 一个实例化对象,然后再使用其公有方法,例如:

jQuery('button').text()

但是这还看不出 跟 jQuery.fn.init.prototype 有什么关联,再看  jQuery.fn.init,jQuery.prototype 赋值给了jQuery.fn ,init 是其对象属性上的一个方法

    jQuery.fn = jQuery.prototype = {
        init:function(){
            //其他代码
            return this;
        },
      // .... 其他方法 jquery:
'1.01' }

但此时问题来了,new jQuery.fn.init() 所返回的新对象并没有继承 jQuery.fn (即 jQuery 原型对象),因为jQuery.fn.init.prototype仅仅是指向了一个function对象的原型,并不包含jQuery.fn。这时,是彻底地将jQuery.fn给封锁了起来。这样是不能使用 jQuery原型对象中公有的方法,

让jQuery.fn.init.prototype指向jQuery.fn

在 jQuery.fn 之后还有如下一段代码:

jQuery.fn.init.prototype = jQuery.fn;

默认情况下 jQuery.fn.init.prototype 是指向的 Object.prototype, 让他指向 jQuery.prototype (即 jQuery.fn),jQuery.fn.init 就继承了 jQuery.prototype,则就可以访问其他公有的方法

在jquery 源码中 jQuery.fn.init.prototype 、 jQuery.prototype 、  jQuery.fn 三者间的关系,我认为应该是:

  • jQuery.prototype,挂载jQuery对象的原型方法;
  • jQuery.fn 是 jQuery.prototype的别名 简单书写
  • jQuery.fn.init.prototype,则是为了让jQuery.fn.init这个工厂方法能够继承jQuery.fn上的原型方法。从而简化最终使用方法,不需要 new即可使用
原文地址:https://www.cnblogs.com/bruce-gou/p/9828898.html