价值、原型和属性的差异

Difference of the value, prototype and property

本文关键字:属性 原型 价值      更新时间:2023-09-26

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

我得到静态方法。但是无法使用所有这些方法获取它如何返回和元素数组。

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

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

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

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

但他们也做了两件[奇怪的]事情:

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

我认为他们需要/想要做所有这些事情才能做到万无一失,但他们的代码是一团糟 - 从该对象文字开始,然后分配 init 原型的东西。

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

它基本上是这样构造的:

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

除了ajQuerybjQuery.prototype.init.

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

1(模式需要从jQuery.fn.init.prototypejQuery.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; };