2012-08-27 46 views
5

行!首先,这个问题来自一个在jQuery世界中挖掘得太深(并且可能会迷路)的人。价值,原型和财产的区别

在我的可测量类,我发现了jQuery的主要模式是这样的(如果需要修正wellcomed):

(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方法。到这个数组。

我得到了静态方法。但无法得到它如何返回以及所有这些方法的元素数组。

+0

@adnan thanx的编辑 – Lupus

回答

8

我也不喜欢那种模式。他们有一个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.fninit功能 - 它自己的原型。这可能允许Extending $.fn.init function,但非常混乱

我认为他们需要/想做到这一切是傻瓜证明,但他们的代码是一个烂摊子 - 后开始与该对象的文字和分配初始化原型的东西。

+1

+1鄙视这种模式 – Adi

+0

是否覆盖构造函数如何获得'this',即返回的值指向jQuery?......不,这是#2奇怪的事情是什么...什么是#1奇怪的事情对于? – 2012-09-26 00:02:17

+0

这实质上是一个入侵'this'看起来像一个jQuery'这个' – 2012-09-26 00:15:37

3

如果您将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; };