jQuery插件和全局变量 [英] Jquery Plugins and global variables

查看:133
本文介绍了jQuery插件和全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读jQuery插件,作者在官方指南中指出:

I'm reading up on jQuery plugins, and in the official guide the author states:

但是等等!我知道并喜欢的我很棒的美元符号在哪里?它仍然存在,但是要确保您的插件不会与可能使用美元符号的其他库冲突,这是传递jQuery的最佳实践到一个IIFE(立即调用函数表达式),该函数将其映射到美元符号,这样它就不会在执行范围内被另一个库覆盖."

"But wait! Where's my awesome dollar sign that I know and love? It's still there, however to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution."

这是示例代码:

(function( $ ) {
    $.fn.myPlugin = function() {

        // Do your awesome plugin stuff here

    };
})( jQuery );

我的问题是,为什么IIFE是必需的,如果没有IIFE,可能发生哪些碰撞示例?执行后,$参数将由Jquery全局变量替换,因此IIFE会更改全局变量.对我来说,这似乎表明发生碰撞的可能性和以前一样.我知道我在这里想念什么.在此先感谢您的帮助!

My question is, why is the IIFE necessary, and what are some examples of collisions that could occur without it? Upon execution, the $ parameter will be replaced by the Jquery global variable, and therefore a global variable is being altered by the IIFE. To me, that seems to suggest that collisions are just as likely as before. I know I'm missing something here. Many thanks in advance for your help!

推荐答案

$符号被其他库(例如原型 MooTools .因此,$全局变量可能不引用jQuery.这就是 jQuery的noConflict方法存在的原因.

The $ symbol is used as a global variable by other libraries such as prototype and MooTools. Therefore the $ global variable might not refer to jQuery; this is the reason jQuery's noConflict method exists.

因此,如果要在除jQuery之外还使用原型或MooTools的页面上使用您的插件,则不能确定$将引用jQuery,但可以假定jQuery变量将.如果您正在编写插件,则希望使其尽可能易于他人使用.因此,您想使其无缝地与其他库一起使用.

So if your plugin was to be used on a page that utilizes either prototype or MooTools in addition to jQuery, you cannot be sure that $ will be referring to jQuery, but you can assume that the jQuery variable will. If you're writing a plugin you want to make it as easy as possible for others to use. Therefore you want to make it seamless for use with other libraries.

IIFE使得这种安全成为可能,并且仍然具有在代码中使用$的便利.如果您总是可以使用jQuery引用而不是$来引用jQuery库,则不需要IIFE.

The IIFE makes it possible to have this safety and still have the convenience of using $ in your code. If you're fine always referring to the jQuery library with the jQuery reference instead of $ then the IIFE is unnecessary.

这篇关于jQuery插件和全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆