jQuery如何实现使$成为jQuery函数的别名? [英] How does jQuery achieve making $ an alias for the jQuery function?
问题描述
我在将$符号换成jQuery函数的别名时遇到了一些麻烦,尤其是在插件中.您能解释一下jQuery如何实现这种别名:它如何将'$'定义为jQuery函数的别名?那是第一个问题.
I’m having a little trouble wrapping my head around the $ sign being an alias for the jQuery function, particularly in a plugin. Can you explain how jQuery achieves this aliasing: how does it define '$' to be an alias for the jQuery function? That's the first question.
其次,您能否解释一下以下代码如何/为何在插件的定义中将"$"映射到jQuery函数,以及为什么不这样做,您的插件可能会与可能使用美元的其他库发生冲突签名?
Secondly, can you explain how/why the following code works to map '$' to the jQuery function in a plugin's definition and why if you don't do this, your plugin could collide with other libraries that might use the dollar sign?
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})(jQuery);
推荐答案
可以将函数(如javascript中的任何对象)分配给变量.该变量可以具有任何名称(遵循JS变量命名规则). "$"满足命名规则,因此为简洁起见,jQuery函数别名为"$".考虑以下示例:
A function, like any object in javascript, can be assigned to a variable. This variable can have any name (that follows the JS variable naming rules). "$" satisfies the naming rules, so the jQuery function is aliased to "$" for brevity. Consider the following example:
var myFn = function() { alert('myFunc'); };
var $ = myFn;
$();
// alerts 'myFunc'
这篇关于jQuery如何实现使$成为jQuery函数的别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!