这些功能有什么区别?

dop*_*man 8 javascript jquery

我有Jquery in Action这本书,在谈到消除与其他库的冲突时,它提到了这三个函数.但是,我不知道他们之间有什么区别,也不明白这本书的解释.

jQuery(function($) {
    alert('I"m ready!');
});

var $ = 'Hi!';
jQuery(function() {
    alert('$ = ' + $);
});

var $ = 'Hi!';
jQuery(function($) {
    alert('$ = ' + $);
});
Run Code Online (Sandbox Code Playgroud)

有谁知道有什么区别?谢谢.

pim*_*vdb 2

如果你采用简化版本可能会更容易理解。第一个就绪函数除了发出警报之外并没有做更多的事情。另外两个很有趣。

函数具有作用域,这意味着当您在函数内部使用变量时,它将在层次结构中向上移动,直到找到为止。

在第二个就绪函数中,$将上升到 ,因为如果您从函数内部开始上升,Hi!则没有其他函数。$

然而,在第三个就绪块中,$不会转到 the,Hi!因为它有一个更接近的定义 - 作为参数传递的定义 ( function($) {)。这$将是 jQuery 函数(即在该函数中$ == jQuery),因为这就是 jQuery 的就绪功能的实现方式。

所以:

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
});
Run Code Online (Sandbox Code Playgroud)

现在你的问题是与其他库的冲突。其他库(例如 Prototype)也使用该$符号,因为它是调用库的便捷快捷方式。如果您使用您提供的最后一个就绪函数,您可以确定该函数内,$将引用 jQuery,因为 jQuery 将自身传递给该函数(作为第一个参数)。

例如,在第二个就绪函数中,$也可能已设置为 Prototype,并且您不确定是否使用$. 在你的例子中,它是Hi!而不是 jQuery。如果它是原型,那就是同样的事情。考虑:

// Prototype is loaded here, $ is referring to Prototype

jQuery(function() {
    $('selector').addClass('something'); // Oops - you're calling Prototype with $!
});
Run Code Online (Sandbox Code Playgroud)

另一方面:

// 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 $
});
Run Code Online (Sandbox Code Playgroud)