值、原型和属性的区别

IT技术 javascript jquery oop reverse-engineering
2021-02-02 03:44:35

行!首先,这个问题来自一个在 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等。到这个数组。

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

2个回答

我也不喜欢这种模式。他们有一个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 原型。

不,原型对象上constructor 属性与功能无关。我不知道你说的“让初始化this看起来像一个 jQuerythis是什么意思——它只是通常的“类”模式
2021-03-17 03:44:35
当然,虽然你也有这样的反向引用 …prototype.constructor.…
2021-03-22 03:44:35
这本质上是一个让 initsthis看起来像 jQuery的黑客this
2021-03-27 03:44:35
不要忘记无尽的原型循环,f.ex: new $.fn.init.prototype.init.prototype.init.prototype.init('body');
2021-03-29 03:44:35
是否覆盖构造函数如何获得this,即返回的值指向 jQuery?...不,这就是 #2 奇怪的东西是什么......#1 奇怪的东西是什么?
2021-04-05 03:44:35

如果您将 API 视为方法的外部集合,而将 jQuery 函数视为包装器,则更容易理解。

它基本上是这样构造的:

function a() { return new b();}
a.prototype.method = function() { return this; }
function b() {}
b.prototype = a.prototype;

除了aisjQuerybis jQuery.prototype.init

我确信 Resig 将 api 构造函数放在 init 原型中是有他的理由的,但我看不到它们。除了贝尔吉提到的那些之外,还有一些奇怪的地方:

1)模式需要从jQuery.fn.init.prototypeto的参考副本jQuery.prototype,这允许一个奇怪的无限循环:

var $body = new $.fn.init.prototype.init.prototype.init.prototype.init('body');

2) 每个 jQuery 集合实际上都是 的一个实例jQuery.fn.init,但是由于它们引用了相同的原型对象,它让我们“认为”该集合是 的实例jQuery你可以像这样做同样的巫术:

function a(){}
function b(){}
a.prototype = b.prototype;
console.log( new b instanceof a); // true
console.log( new a instanceof b); // true

旁注:我个人使用了以下具有类似结果的构造函数模式,但没有奇怪之处:

var a = function(arg) {
    if (!(this instanceof a)) {
        return new a(arg);
    }
};
a.prototype.method = function(){ return this; };