扩展 jQuery 的奇怪语法
我最近在另一篇文章中看到了这段代码( jQuery Set Cursor Position in Text Area )
new function($) {
$.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
} (jQuery);
经过很长时间试图理解它在做什么后,我终于发现它只是创建一个带有参数 $ 的新函数,然后使用 jQuery 作为参数值调用它。
所以实际上,它只是这样做:
jQuery.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
原始的、更令人困惑的版本的原因是什么?
I recently saw this code on another post ( jQuery Set Cursor Position in Text Area )
new function($) {
$.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
} (jQuery);
After too long trying to understand what it was doing I finally figured out that it's just creating a new function with a parameter $ and then invoking it with jQuery as the parameter value.
So actually, it's just doing this:
jQuery.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
What's the reason for the original, more confusing version?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于大型代码块,使用
$
比jQuery
好得多。当使用多个库时,人们经常会禁用
$
快捷方式,因为许多库都使用它。这样编写代码可以让用户使用快捷方式编写代码,而不必担心与其他库冲突。由于该网站适用于广泛的受众,因此无论用户是否启用了$
,使用该代码都是最有可能起作用的。For large blocks of code using
$
is much nicer thanjQuery
.When using multiple libraries, people will often disable the
$
shortcut because many libraries use it. Writing the code like that allows users to write code with the shortcut without worrying about conflicting with other libraries. And since this site applies to a wide audience, using that code is the most likely to work whether or not the user has$
enabled.由于其他 JavaScript 库可能全局使用
$
,因此您的库应显式引用jQuery
以防止冲突。通过创建带有参数$
的函数,您可以将jQuery
对象绑定到该函数范围内的该变量。这使您可以安全地显式指定jQuery
对象,并方便地使用$
简写。这是我习惯看到的模式:
Since other JavaScript libraries may use
$
globally, your library should explicitly referencejQuery
to prevent conflicts. By creating a function with parameter$
, you can bind thejQuery
object to that variable within the scope of that function. This gives you the safety of explicitly specifying thejQuery
object AND the convenience of using the$
shorthand.This is the pattern I am used to seeing:
和
and