小编典典

价值,原型和特性的差异

javascript

好!首先,这个问题来自于一个在jQuery宇宙中挖得太深(很可能迷路)的人。

在我的研究中,我发现了jquery的主要模式是这样的(如果需要的话,欢迎改正):

(function (window, undefined) {

   jQuery = function (arg) {
      // The jQuery object is actually just the init constructor 'enhanced'
      return new jQuery.fn.init(arg);
   },
   jQuery.fn = jQuery.prototype = {
      constructor: jQuery,
      init: function (selector, context, rootjQuery) {
         // get the selected DOM el.
         // and returns an array
      },
      method: function () {
         doSomeThing();
         return this;
      },
      method2: function () {
         doSomeThing();
         return this;,
         method3: function () {
            doSomeThing();
            return this;
         };

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

         jQuery.extend = jQuery.fn.extend = function () {

            //defines the extend method 
         };
         // extends the jQuery function and adds some static methods 
         jQuery.extend({
            method: function () {}

         })

      })

$启动时,jQuery.prototype.init启动并返回一个元素数组。但我不明白它是如何增加了jQuery的方法类似.css.hide等。到这个数组。

我得到了静态方法。但是用所有这些方法都无法获得返回值和元素数组的方式。


阅读 239

收藏
2020-05-01

共1个答案

小编典典

我也不喜欢这种模式。他们有一个init函数,它是所有jQuery实例的构造jQuery函数- 函数本身只是对象创建过程的包装器,包括new

function jQuery(…) { return new init(…); }

然后,他们将那些实例的方法添加到init.prototype对象中。该对象在处作为接口公开jQuery.fn。此外,他们将prototypejQuery函数的属性设置为该对象-
对于不使用该fn属性的用户。现在你有

jQuery.prototype = jQuery.fn = […]init.prototype

但是他们也做两件事:

  • 覆盖constructor原型对象的属性,将其设置为jQuery函数
  • 公开init功能jQuery.fn-自己的原型。这可能允许扩展$ .fn.init函数,但非常令人困惑

我认为他们需要/想要做所有这些事情以防万一,但是他们的代码很烂-从该对象文字开始,然后分配init原型。

2020-05-01