为什么要像这样编写代码Jquery [英] Why write code Jquery like this

查看:86
本文介绍了为什么要像这样编写代码Jquery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要像这样编写代码Jquery?

Why write code Jquery like this?

(function ($) {
    $(function () {
     .......
    });
})(jQuery);


推荐答案

这称为闭包,以避免与其他库冲突正在使用 $ 。这样,通过传递 jQuery 作为参数,您可以确保在该函数中使用 $

This is called a closure to avoid conflicts with other libraries which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.

(function ($) {
   $(function () {
    .......
   });
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.



来自文档:



from the docs:


最佳做法是将jQuery传递到IIFE(立即调用函数表达式),该函数将其映射到美元符号,以便在执行范围内不能被另一个库覆盖。

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.

这篇关于为什么要像这样编写代码Jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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