jQuery如何擁有$對象構造函數和與$的關聯的方法?

[英]How does jQuery have the $ object constructor and the methods associated with the $?


How is it that jQuery can do $("#foo").addClass("bar") and $.ajax()?

jQuery如何實現$(“#foo”).addClass(“bar”)和$.ajax()?

I'm creating a micro javascript framework and want to create a new instance of an object, such as $("#hello"). With this object there are associated methods, such as addClass, css, etc, just like with jQuery. So I could do something like

我正在創建一個微javascript框架,並希望創建一個對象的新實例,比如$(“#hello”)。有了這個對象,就有了相關的方法,比如addClass、css等,就像jQuery一樣。我可以這樣做

$("#foo").addClass("remove").css("color", "red");

I have been successful in creating this. However, when I want to call a method from this object, such as $.ajax, the constructor function is overwritten, and I can call $.ajax, but not $("#foo").

我已經成功地創造了這個。但是,當我想從這個對象調用一個方法時,比如$。ajax,構造函數被覆蓋,我可以調用$。ajax,但不是$(" # foo ")。

Basically, how can jQuery do both?

基本上,jQuery如何做到這兩點呢?

4 个解决方案

#1


10  

OK, the $ function is not only a function but an object, like all functions. So it can have methods. That's all that ajax is, a method of the $ function. So we can start off by doing this:

$ function不僅是一個函數也是一個對象,就像所有的函數一樣。所以它可以有方法。這就是ajax, $函數的一種方法。我們可以這樣開始

$ = function(obj) {
  // some code 
};
$.ajax = function (arg1, arg2) {
  // some ajax-y code
};

So far so good. Now, what on earth do we put in the $ function? Well it has to return an object and that object has to have some nice methods defined on it. So we'll need a constructor function (to give us new objects) and a prototype (to provide the nifty methods for those objects).

目前為止一切都很順利。那么,我們究竟在$函數中加入了什么呢?它必須返回一個對象這個對象必須有一些很好的方法。因此,我們需要一個構造函數(為我們提供新的對象)和一個原型(為這些對象提供漂亮的方法)。

$ = function(obj) {
  var myConstructor = function (obj) {
    this.wrappedObj = obj;
  };

  myConstructor.prototype = {
    niftyMethod: function () {
      // do something with this.wrappedObj
      return this; // so we can chain method calls
    },
    anotherNiftyMethod: function (options) {
      // do something with this.wrappedObj and options
      return this; 
    }
  };

  return new myConstructor(obj);
};

So there we have it. We can do this:

就得到了。我們可以這樣做:

var mySnazzObject = $("whatever");
mySnazzObject.niftyMethod().anotherNiftyMethod(true);        

And we can do this:

我們可以這樣做:

$.ajax("overthere.html", data);

Obviously jQuery does a heck of a lot more than that, and it does it in some really impressive ways, but that's the general idea.

顯然,jQuery做的比這多得多,它以一些令人印象深刻的方式進行,但這是一個總體的想法。

UPDATE: AS @Raynos was kind enough to observe without supplying a constructive answer, my original code would create the prototype ad infinitum. So we make use of an anonymous autoexecuting function to declare the constructor and prototype separately:

更新:因為@Raynos很好地觀察而不提供建設性的答案,我的原始代碼將創建原型,直到無限。因此,我們使用匿名自動執行函數來分別聲明構造函數和原型:

(function () {
  var myConstructor = function (obj) {
    this.wrappedObj = obj;
  };

  myConstructor.prototype = {
    niftyMethod: function () {
      // do something with this.wrappedObj
      return this; // so we can chain method calls
    },
    anotherNiftyMethod: function (options) {
      // do something with this.wrappedObj and options
      return this; 
    }
  };

  var $ = function(obj) {
    return new myConstructor(obj);        
  };

  $.ajax = function (arg1, arg2) {
    // some ajax-y code
  };

  window.$ = $;  
}());

#2


15  

$ = function(arg) { console.log("$ function called with " + arg); }
$.ajax = function(arg) {console.log("$.ajax called with " + arg);}
$('foo');
$.ajax('bar');

http://jsfiddle.net/ac7nx/

http://jsfiddle.net/ac7nx/

I don't think there's any magic here. $ is just a name for the global function. Just keep in mind that in javascript, functions are first class objects that can have their own properties, including sub-functions, which is what $.ajax is.

我不認為這有什么神奇的。$只是全局函數的一個名稱。請記住,在javascript中,函數是第一類對象,它們可以有自己的屬性,包括子函數,這就是$。ajax。

Since you mentioned the constructor function, I should note that there are no OO objects being used here, just regular functions (no new keyword), so constructor functions don't play into this. If you are using the new keyword, that is probably where you are getting confused. If you want $('#foo') to return a new object, then inside the $ function's code you should create a new object using new and return that, which is what jQuery does, but the $ function itself is not a constructor and should not be called with new. Or in the case of something like $('#someID'), inside that function jQuery is getting an element object from the DOM and then returning that object, but still $ is just a regular function whose return value is an object, not a constructor function.

由於您提到了構造函數,我應該注意這里沒有使用OO對象,只有常規函數(沒有新的關鍵字),所以構造函數不參與其中。如果您使用的是新關鍵字,那么您可能會感到困惑。如果您希望$('#foo')返回一個新對象,那么在$函數的代碼中,您應該使用new創建一個新對象並返回它,這是jQuery所做的,但是$函數本身不是構造函數,不應該使用new調用它。或者對於$('#someID')這樣的函數,jQuery從DOM中獲取一個元素對象,然后返回該對象,但$仍然是一個常規函數,其返回值是對象,而不是構造函數。

#3


1  

Two different things:

兩個不同的東西:

$.ajax is a prototyped function of jQuery called ajax.

美元。ajax是jQuery的原型函數,稱為ajax。

While $('foo') is a call of the jQuery function and depending on the type of foo it reacts in different ways. At http://api.jquery.com/jQuery you can see that jQuery (almost the same as $) can react on three different types: selectors, html or callbacks.

$('foo')是jQuery函數的調用,取決於foo的類型,它以不同的方式反應。在http://api.jquery.com/jQuery中,您可以看到jQuery(幾乎與$相同)可以對三種類型作出反應:選擇器、html或回調。

#4


0  

You can imitate the magic jQuery behaviour as following:

您可以模仿jQuery的神奇行為如下:

//define
var _$ = {};
var $ = function(selector) {
           _$.html = function(args) {
                    alert("Doing the method 'html' with arguments " + args 
                           + " for selector " + selector);
                    return _$; //needed for pipeline
        };
        return _$; 
};

$.ajax = function(args){alert("Doing the method 'ajax' "); }

//and try
$("selector1").html("args1").html("args2");
$.ajax("args2");

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/06/11/725ba687a1df01300d2d4bc15358b3e5.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com