0

我正在阅读一些使用 requirejs 来处理 jquery 的代码。

它使用

require([
'jquery',
], 

function(
$
){} );

我想知道为什么只使用 $ 对于所有 jquery 函数就足够了?

4

2 回答 2

1

jquery如果define函数已经定义, jQuery 将自行定义模块。

以下代码在 jquery.js 中。

if ( typeof module === "object" && module && typeof module.exports === "object" ) {
    // Expose jQuery as module.exports in loaders that implement the Node
    // module pattern (including browserify). Do not create the global, since
    // the user will be storing it themselves locally, and globals are frowned
    // upon in the Node module world.
    module.exports = jQuery;
} else {
    // Otherwise expose jQuery to the global object as usual
    window.jQuery = window.$ = jQuery;

    // Register as a named AMD module, since jQuery can be concatenated with other
    // files that may use define, but not via a proper concatenation script that
    // understands anonymous AMD modules. A named AMD is safest and most robust
    // way to register. Lowercase jquery is used because AMD module names are
    // derived from file names, and jQuery is normally delivered in a lowercase
    // file name. Do this after creating the global so that if an AMD module wants
    // to call noConflict to hide this version of jQuery, it will work.
    if ( typeof define === "function" && define.amd ) {
        define( "jquery", [], function () { return jQuery; } );
    }
}
于 2013-07-07T03:24:18.820 回答
0

看看如何将 RequireJS 与 jQuery 一起使用

但是,是的,您只需要$(witch 与 相同jQuery),因为 jQuery 提供的每个方法(或插件)都封装在该变量中。

如果您requirejs用于加载文件并且您不这样做,$则将是未定义的。

来自网站的示例:

require(['jquery'], function( $ ) {
    console.log( $ ) // OK
});

require(['jquery'], function( jq ) {
    console.log( jq ) // OK
});

require(['jquery'], function( ) {
    console.log( $ ) // UNDEFINED!
});
于 2013-07-07T03:09:17.690 回答