如果您采用简化版本,可能会更容易理解。第一个准备就绪的功能并不比提醒更多。另外两个很有意思。
函数具有范围,这意味着当您在一个变量中使用变量时,它将在层次结构中上升直到找到它。
在您的第二个就绪功能中,$
将上升到Hi!
,因为如果您在该功能内部开始时没有其他$
。
但是,在第三个就绪块中,$
将不会转到Hi!
,因为它的定义更接近 - 作为参数传递的定义(function($) {
)。这$
将是jQuery函数(即在那个函数$ == jQuery
),因为这是如何实现jQuery的ready功能。
所以:
var $ = 'Hi!';
jQuery(function() {
alert('$ = ' + $); // in this scope, $ will refer to the 'Hi!'
});
jQuery(function($) { // the $ here will 'shadow' the $ defined as 'Hi!'
alert('$ = ' + $); // in this scope, $ will refer to jQuery
});
现在你的问题是关于与其他图书馆冲突。其他库(例如原型)也使用$
符号,因为它是调用库的方便捷径。如果你使用你提供的最后一个就绪函数,你可以是当然那个函数里,$
将引用jQuery,因为jQuery将自身传递给该函数(作为第一个参数)。
在第二个就绪函数中,例如$
也可能已设置为Prototype,并且您不确定是否使用$
调用jQuery。在你的例子中,它是Hi!
而不是jQuery。如果是Prototype,它是一样的。试想一下:
// Prototype is loaded here, $ is referring to Prototype
jQuery(function() {
$('selector').addClass('something'); // Oops - you're calling Prototype with $!
});
在另一方面:
// Prototype is loaded here, $ is referring to Prototype
jQuery(function($) { // this $ is shadowing Prototype's $, this $ is jQuery
$('selector').addClass('something'); // Yay - you're calling jQuery with $
});
@ Beefyhalo - '$'是否具有特殊含义,如果它已经在'jQuery()'处理程序中了? 也就是说,在'jQuery(function(argument){...})中传递的参数是否仍然(有效)解析为与$'相同的东西? – dopatraman
jQuery将自己分配给jQuery处理程序中的第一个参数。无论第一个参数的名称是什么,jQuery都会被分配给它。所以对于'jQuery(function(argument){...','jQuery(function($){...'和'jQuery(function(someOtherArgument){...'),参数=== $ === someOtherArgument' – beefyhalo
@ Beefyhalo - 谢谢,这有助于澄清事情 – dopatraman