2009-09-22 73 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