Won*_*and 0 javascript jquery lambda
我正在尝试进入Javascript Lambda方法,但我仍然非常困惑的是非常灵活的方式可以定义东西和变量范围.
例如,我正在查看以下插件的代码,除了代码的其他部分,我不清楚,我对代码的组织方式感兴趣.
//////////////////////////////////////////////////////////////////////////////////
// Cloud Zoom V1.0.2
// (c) 2010 by R Cecco. <http://www.professorcloud.com>
// MIT License
//
// Please retain this copyright header in all versions of the software
//////////////////////////////////////////////////////////////////////////////////
(function ($) {
$(document).ready(function () {
$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
});
function CloudZoom(jWin, opts) {
....
}
$.fn.CloudZoom = function (options) {
....
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
现在我想$并且$.fn是由jQuery定义的2个对象,它们用于为插件代码创建单独的命名空间/范围及其变量
我想对以下几点有所了解:
(function($){})(jQuery)这是什么意思 ?function($)在我看来一个匿名(lambda)函数,它作为参数,$但我不确定最后的(jQuery)东西的含义.
内部功能function CloudZoom(jWin, opts)只能在内部范围内使用吗?
$.fn.CloudZoom正在"扩展" $.fn对象......为什么它们与上述函数具有相同的名称?
代码$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();实际上是在调用哪个函数?
1 function($){})(jQuery) etc是立即调用的函数表达式(IIFE)并且简单地提供局部范围的$变量jQuery以避免$与其他插件的冲突.是的,它只是一个匿名函数,可以立即调用以提供其他声明的范围.
IIFE基本上是调用这样的匿名函数(它没有名字):
function(){}
Run Code Online (Sandbox Code Playgroud)
用括号括起来使其可引用:
(function(){})
Run Code Online (Sandbox Code Playgroud)
所以你可以这样做立即运行它:
(function(){})();
Run Code Online (Sandbox Code Playgroud)
您当然可以将参数传递给它:
(function(param1, param2){
// param1 = 1
// param2 = 2
})(1,2);
Run Code Online (Sandbox Code Playgroud)
所以他们的例子是这样做的:
(function($){
// $ is now the same as jQuery!
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
是.该函数应仅在外部函数的范围内可用.
没有我能想到的.命名可以是任何东西,只要它不冲突.(我通常ProperCase用于类函数和pascalCase.fn扩展名).
$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom()从以下函数this返回的jQuery对象/集合调用以下函数$('.cloud-zoom, .cloud-zoom-gallery'):
$.fn.CloudZoom = function (options) {
....
var $thisIsTheSelectorResult = this; // == $('.cloud-zoom, .cloud-zoom-gallery')
};
Run Code Online (Sandbox Code Playgroud)