javascript - 值、原型(prototype)和属性的区别

标签 javascript jquery oop reverse-engineering

好的!首先,这个问题来自一个在 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 启动并返回一个元素数组。但我不明白它是如何添加像 .css.hide 等 jQuery 方法的。到这个数组。

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

最佳答案

我也不喜欢那个图案。它们有一个 init 函数,它是所有 jQuery 实例的构造函数 - jQuery 函数本身只是用 new 创建的对象的包装器:

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

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

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

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

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

我认为他们需要/想要做所有这一切以确保万无一失,但他们的代码一团糟——从对象字面量开始,然后分配初始化原型(prototype)。

关于javascript - 值、原型(prototype)和属性的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12143590/

相关文章:

javascript - 获取调用 onclick 函数的元素

javascript - 为什么 javascript ln 被称为日志?

javascript - Node + Express : Does Express clone the req and res objects for each request handler?

javascript - HTML/JS : Scroll to Top Visual Artifact

javascript - 自动突出显示焦点上的输入字段

javascript - 将图像添加到 jquery 自动完成搜索

javascript - 使用 Jest 部分模拟 React 模块

PHP访问对象的数据

java - Java中的引用变量到底是什么?它与其他变量有何不同?

c - 如何实现继承: error: conflicting declaration ‘typedef struct