2009-09-22 76 views
7

我在想,$如何。在$ .ajax({...});工作?它對我沒有意義。當然.ajax作爲一個成員是有道理的,但是$不是一個變量名?還是它?它是如何定義的?

+6

這是一個函數名,擁有jQuery代碼的讀取。該函數有效地返回一個具有成員'ajax'的JQuery對象。 – Lazarus 2009-09-22 12:16:47

+1

@Lazarus:實際上,儘管$函數在調用時會返回一個jQuery對象,但這不是這裏發生的事情。 $與JS中的所有函數一樣,都是一個對象,並且可以擁有自己的屬性(即ajax)。調用$(「」)時返回的jQuery對象沒有ajax屬性(嘗試typeof $(「」).ajax而不是typeof $ .ajax) – figha 2009-09-23 14:44:28

回答

16

$與jQuery相同。也就是說,您可以編寫jQuery.ajax(...)等。

令人困惑的部分是$是Javascript變量名稱中的合法字符。它沒有任何特殊的含義,比如在PHP或Perl中。

10

從源:

// Map over jQuery in case of overwrite 
_jQuery = window.jQuery, 
// Map over the $ in case of overwrite 
_$ = window.$, 

jQuery = window.jQuery = window.$ = function(selector, context) { 
// The jQuery object is actually just the init constructor 'enhanced' 
    return new jQuery.fn.init(selector, context); 
}, 

這是一個功能(第一類對象)與性質,例如你提到的ajax功能。

「$」是變量名稱的有效字符,正如您從代碼段中看到的,$jQuery相同。

1

$是可以在Javascript變量名中使用的唯一合法字符之一。 JQuery和其他庫利用初始化$作爲初始化jQuery對象的函數。

如果我沒有記錯的代碼看起來有點像下面這樣:

$ = window.jQuery = function(){ 
    return new jQuery(args); 
} 
2

$這是jQuery庫中的定義是jQuery的短的參考。 您也可以下載庫,看到了第一線:

var 
    // Will speed up references to window, and allows munging its name. 
    window = this, 
    // Will speed up references to undefined, and allows munging its name. 
    undefined, 
    // Map over jQuery in case of overwrite 
    _jQuery = window.jQuery, 
    // Map over the $ in case of overwrite 
    _$ = window.$, 

這種「窗口$」,「$」屬於窗口對象的環境。

1

在JavaScript中,函數是對象(可以由變量包含)。因此,它們可以具有屬性(和方法,這些屬性只是函數的值)。試試這個:

function test() { 
    alert("hey!"); 
} 
test.foo = function (msg) { 
    alert("you said: "+msg); 
}; 

test(); //alerts "hey!" 
test.foo("123") //alerts ""you said: 123". 

//note that I'm not calling test().foo(), 
//as test() returns nothing, though it could 
//return an object (with a foo() or any other method itself!) 

這就是jQuery發生的情況。

2

正如在許多JavaScript資源的說明,包括Mozilla's JavaScript Guide

一個JavaScript標識符必須以字母開頭,下劃線(_)或美元符號($);後續字符也可以是數字(0-9)。由於JavaScript區分大小寫,所以字母包括字符「A」到「Z」(大寫)以及字符「a」到「z」(小寫)。

所以在JavaScript以下都是合法的(雖然是不明智的):

var $ = function() {}; 

var ____ = 0; 

var __$__$ = 1; 

function _$_$_$_(_, __, $_$) { 
    return (_ * __) + $_$; 
} 

alert(_$_$_$_(3,2,1)); // shows 7