gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 04:32:58 28 4
gpt4 key购买 nike

我正在研究 jQuery 源代码的工作原理,我知道 jQuery 对象只是转发对 jQuery.fn.init 的调用,其中 jQuery.fn 只是一个引用到 jQuery.prototype

然后在源码中,有这样一行:

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

有注释解释了代码的作用,但我还是看不懂。

  1. 谁能解释一下这行代码是什么意思?它在谈论什么后面的实例化以及为什么我们需要将 init 的原型(prototype)设置为 jquery 的原型(prototype)?

  2. jQuery 源代码使用 jQuery.fn 而不是直接使用 jQuery.prototype 是否有原因(例如避免冲突或可读性等)?

最佳答案

(假设您对原型(prototype)继承有一定的了解,则撰写此回复。如果您不了解,则需要阅读有关它的文章以完全了解正在发生的事情。尝试在 Google 上搜索“原型(prototype)继承 javascript”。 )

当在内部创建一个新的 jQuery 对象时,它是用 new jQuery.fn.init() 创建的。 init 是一个构造函数,所以在这个构造函数上设置prototype 属性可以让新创建的 jQuery 对象继承这个原型(prototype)的所有属性(jQuery.prototype 的所有方法)。 fn).

如果只是使用 new jQuery(),正如您所暗示的那样,该对象将继承自 jQuery.prototype 但是 jQuery 函数将被执行,正如您所知很多。而是使用 init 构造函数,因为它不包含 jQuery 函数的包袱。将 jQuery.prototype 设置为与 jQuery.fn.init.prototype 相同只允许您执行 jqueryobject instanceof jQuery,这很好,所以这就是 jQuery 对象具有原型(prototype)的原因。

关于javascript - 理解 jquery 源代码 - jquery.fn.init,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13440907/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com