我有本书 Jquery in Action,它在谈到消除与其他库的冲突时提到了这三个功能。但是不知道它们有什么区别,也不明白书上的解释。
jQuery(function($) {
alert('I"m ready!');
});
var $ = 'Hi!';
jQuery(function() {
alert('$ = ' + $);
});
var $ = 'Hi!';
jQuery(function($) {
alert('$ = ' + $);
});
谁知道有什么区别?谢谢。
最佳答案
如果你采用简化版本,它可能更容易理解。第一个准备就绪的功能只是发出警报。另外两个很有趣。
函数有作用域,这意味着当您在一个函数中使用一个变量时,它会在层次结构中上升,直到找到它为止。
在您的第二个就绪函数中,$
将上升到 Hi!
,因为如果您从上开始就没有其他 $
在函数内部。
但是,在第三个就绪 block 中,$
不会转到 Hi!
,因为它有一个更接近的定义 - 作为参数传递的定义( 函数($){
)。此 $
将是 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
});
现在您的问题是关于与其他库的冲突。其他库(例如 Prototype)也使用 $
符号,因为它是调用库的便捷快捷方式。如果您使用您提供的最后一个就绪函数,您可以确定在该函数内部,$
将引用 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 $
});
关于javascript - 这些功能有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7111527/