简体   繁体   English

理解jquery源代码 - jquery.fn.init

[英]understanding jquery source code - jquery.fn.init

I am looking into how jQuery source code works, I understand the jQuery object just forwards a call to jQuery.fn.init where jQuery.fn is just a reference to jQuery.prototype . 我正在研究jQuery源代码是如何工作的,我理解jQuery对象只是转发对jQuery.fn.init的调用,其中jQuery.fn只是对jQuery.prototype的引用。

Then in the source code, there is this line: 然后在源代码中,有这一行:

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

There is a comment to explain what the code does but I still can't understand it. 有一个注释来解释代码的作用,但我仍然无法理解它。

  1. Can someone explain what does this line of code means? 有人可以解释一下这行代码意味着什么吗? what later instantiation is it talking about and why do we need to set init's prototype to jquery's prototpe? 它后面的实例化是在讨论什么,为什么我们需要将init的原型设置为jquery的prototpe?

  2. is there a reason (like avoiding conflicts or readability or whatever) that jQuery source code is using jQuery.fn instead of using jQuery.prototype directly? jQuery源代码使用jQuery.fn而不是直接使用jQuery.prototype是有原因(比如避免冲突或可读性等)吗?

(This response is written assuming you have some understanding of prototypal inheritance. If you don't, you need to read an article about it to fully understand what's going on. Try doing a Google search for "prototypal inheritance javascript".) (这个回答的编写假设您对原型继承有一定的了解。如果不这样做,您需要阅读一篇关于它的文章以完全理解正在发生的事情。尝试在谷歌搜索“原型继承javascript”。)

When a new jQuery object is created internally, it is created with new jQuery.fn.init() . 当在内部创建新的jQuery对象时,它是使用new jQuery.fn.init()创建的。 init is a constructor, so setting the prototype property on this constructor allows newly created jQuery objects to inherit all the properties of this prototype (all the methods of jQuery.fn ). init是一个构造函数,因此在此构造函数上设置prototype属性允许新创建的jQuery对象继承此原型的所有属性( jQuery.fn所有方法)。

If just new jQuery() was used, as you seem to suggest, the object would inherit from jQuery.prototype but the jQuery function would be executed, which as you know does a lot . 如果只是new jQuery()被使用,因为你似乎暗示,该对象将继承jQuery.prototype jQuery功能将被执行,正如你知道的确实不少 The init constructor is used instead because it doesn't come with the baggage of the jQuery function. 使用init构造函数是因为它没有附带jQuery函数的包袱。 Setting jQuery.prototype to the same as jQuery.fn.init.prototype just allows you to do jqueryobject instanceof jQuery , which is nice, so that's the reason the jQuery object has a prototype. jQuery.prototype设置为与jQuery.fn.init.prototype相同只是允许你做jqueryobject instanceof jQuery ,这很好,所以这就是jQuery对象拥有原型的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM