javascript - 这些功能有什么区别?

标签 javascript jquery

我有本书 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/

相关文章:

jquery - 如何从 jQuery 自动完成列表中自动选择第一项

javascript - 生成范围 (0 - X) 内的唯一编号,保留历史记录以防止重复

javascript - jQuery 以类似的形式验证单个输入

javascript - 从 Django 模型中生成 JavaScript 对象

javascript - TypeScript 中的类型级 Catalan 函数

javascript - 基本 : Return and stop code execution on JavaScript

javascript - 当我使用 CSS 和 JS 向下滚动时,如何从左向右移动(动画)元素?

javascript 的 unload 和 beforeunload 替代方案

javascript - 在不使用 Promise.all 和 Promise.resolve 的情况下在 JS 中的 promise 之间传递中间数据

javascript - 是否可以使用 css/js 将带有滚动条的元素自动边距元素设置为相同位置?