有人可以解释定义jQuery插件时的语法含义吗? [英] Can someone explain what the syntax means when defining a jQuery plugin?

查看:73
本文介绍了有人可以解释定义jQuery插件时的语法含义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关创建自定义jQuery插件的内容,并对以下语法的含义有些困惑:

I am reading up on creating custom jQuery plugins and am a little confused as to the meaning of the following syntax:

(function($){  
    $.fn.truncate = function() {  
        return this.each(function() { 
        });
     };
})(jQuery);

我知道function($)是一个接受$的匿名函数.我只是不太明白为什么将此函数包装在方括号中,以及以下带有jQuery的方括号组是如何工作的.

I understand that function($) is an anonymous function that accepts the $. I just don't quite understand why this function is wrapped in brackets and how the following sets of brackets with jQuery in them...work.

推荐答案

假定$由jQuery库拥有是不安全的.其他一些JavaScript库/用户可能/确实将该标识符用于其他目的.但是,jQuery始终是jQuery库(禁止任何邪恶的行为者).

It is not safe to assume that $ is owned by the jQuery library. Some other javascript libraries/users may/do use that identifier for other purposes. However, jQuery is always the jQuery library (barring any evildoers).

此匿名函数通过将$快捷方式设置为匿名函数的本地参数,从而方便安全地将jQuery公开为$.由于参数仅会在函数范围内覆盖全局变量,因此不会影响函数外的任何其他用户/库代码.

This anonymous function handily and safely exposes the $ shortcut as jQuery by making it a local parameter to the anonymous function. Since parameters will override any globals only for the scope of a function this will not affect any other user/library code outside of it.

最后,执行匿名函数的位置jQuery作为第一个参数传入,以填充$.

Finally, where the anonymous function is executed jQuery is passed in as the first paramter to fill $.

因此,当归根结底时,这只是插件开发人员所采取的捷径,以便他们可以安全可靠地使用$;如果您不介意在任何地方都使用jQuery,那么这完全是可选的.

So when boiled down, this is just a shortcut taken by plugin developers so that they can safely and reliably use $; if you don't mind using jQuery everywhere instead then this is totally optional.

这篇关于有人可以解释定义jQuery插件时的语法含义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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