問題描述
老實說,我不知道如何縮短標題.
我通過研究 SlidesJS 插件的源代碼學習了如何編寫 jQuery 插件.當我遇到新事物時,我只是問了我的好朋友 Google,而且大多數時候都得到了滿意的答案.不過老實說,我從來沒有努力過.我所知道的是 $
(可能)是一個簡寫的 jQuery 對象構造函數,并且 $()
和 jQuery()
是相同的東西提供包含 jQuery.
不過,最近,我嘗試了解 jQuery 背后的科學以及如何編寫 good jQuery 插件.我遇到了一篇非常好的 文章,其中作者列出了幾個用于創建 jQuery 插件的 模板.因為其余的太復雜了,我無法理解,所以我喜歡第一個:輕量級的開始.現在,這里是上述模板的代碼.
<代碼>/*!* jQuery輕量級插件樣板* 原作者:@ajpiano* 進一步的變化,評論:@addyosmani* 在 MIT 許可下獲得許可*///函數調用前的分號是安全的//網絡連接腳本和/或其他插件//沒有正確關閉.;(函數 ($, 窗口, 文檔, 未定義) {//這里使用 undefined 作為 undefined 全局//ECMAScript 3 中的變量并且是可變的(即它可以//被其他人更改).undefined 不是真的//被傳入所以我們可以確保它的值是//真正未定義.在 ES5 中,undefined 不能再//修改的.//窗口和文檔作為本地傳遞//變量而不是全局變量,因為這個(稍微)//加快解析過程,可以更多//有效地縮小(尤其是當兩者都是//在你的插件中經常引用).//創建一次默認值var pluginName = 'defaultPluginName',默認值 = {屬性名稱:值"};//實際的插件構造函數功能插件(元素,選項){this.element = 元素;//jQuery 有一個擴展方法,可以合并//兩個或多個對象的內容,存儲//結果是第一個對象.第一個對象//通常是空的,因為我們不想改變//未來插件實例的默認選項this.options = $.extend( {}, 默認值, 選項) ;this._defaults = 默認值;this._name = pluginName;this.init();}Plugin.prototype.init = function () {//這里放置初始化邏輯//你已經可以訪問 DOM 元素并且//通過實例的選項,例如這個元素//和 this.options};//一個非常輕量級的圍繞構造函數的插件包裝器,//防止多次實例化$.fn[pluginName] = 功能(選項){返回 this.each(function () {if (!$.data(this, 'plugin_' + pluginName)) {$.data(this, 'plugin_' + pluginName,新插件(這個,選項));}});}})( jQuery, 窗口, 文檔);
我已將評論包括在內,以便在我的問題中引用它們.
我有一個粗略的想法,為什么 window
和 document
被包含在包裝插件的匿名函數的參數中(我不知道是什么否則調用它) 因為它在評論中給出它有點縮短執行時間.但這是如何工作的?包裝插件的上述匿名函數的任何參數都會傳遞到哪里?這些在插件中是如何解決的?
通常,我會這樣做 $(window).resize(function(){})
但在這種情況下不起作用.如果我在插件函數中執行 console.log(window)
,它會顯示未定義".
這讓我想到另一個問題:undefined 是什么?不是分配給未在范圍內定義的對象的數據類型嗎?它如何作為參數傳遞?論點不是必須是對象嗎?評論中寫了幾行關于此的內容,但我一個字都看不懂:<所以我們可以確保它的值是真正未定義的> whaaa?
總結一下:
function($)
究竟是什么意思?- 為什么要在
function($)
的參數中包含window
、document
和undefined
?李> - 如果這樣做,如何訪問實際的
window
和document
對象? 未定義
什么,為什么?
請對我放輕松.我從來沒有為了編寫應用程序的明確目的而將編程語言作為一門學科.我學習了基本的 C 語言,用于為微型核心微控制器編寫面向硬件的低級例程,僅此而已.我確實廣泛地學習了 C++ 和一點點 Java.只是為了讓您知道會發生什么.
當你寫這樣的函數時:
(function (foo, bar) {返回 foo.getElementById(bar);})(文檔,我的元素")
然后立即使用參數 document
和 "myElement"
為參數 foo
和 bar
調用該函數.因此,在函數內部,foo.getElementById(bar)
等價于document.getElementById("myElement")
.
同樣,在您的插件示例中,您會立即使用參數 jQuery, document, window
調用該函數.
function($)
究竟是什么意思?
$
僅表示對傳遞給包裝函數的 jQuery
對象的引用.稍后,當使用 (jQuery, window, document)
調用匿名函數時,函數內部的 $
引用引用了 jQuery
對象.這樣做的原因有很多,其中最重要的是 $
可以更快地鍵入.它還允許用戶將包裝器中的插件應用到 jQuery
的 特定實例,可能由 jQuery.noConflict()
生成.p><塊引用>
我為什么要包含 window
、document
和 undefined
作為 function($)
的參數?p>
您不需要包含這些.原作者的推理是分配函數局部變量來引用這些將縮短解析這些變量所需的時間.我斷言節省的費用微不足道;除非我使用 大量 對 window
和/或 document
的引用,否則我個人不會打擾.
至于 undefined
,原作者包含此內容的目的是確保有人沒有更改 EcmaScript 4 中的 undefined
全局變量(實際上是 ECMAScript 3-- 版本 4 從未成功)或更早版本.同樣,我無法想象會出現這個問題.如果你真的擔心這可能是一個問題,只需在你的函數中包含這樣的內容:
if(typeof undefined !== "undefined") {未定義=無效0;}
<塊引用>
如果我這樣做,我如何訪問實際的 window
和 document
對象?
您所要做的就是確保匿名函數末尾的函數調用傳入實際的(jQuery、窗口、文檔)參數.或者,不要在函數簽名中包含 window
和 document
參數.無論哪種方式,您都將引用 實際 對象,而不管間接級別如何.
未定義
什么,為什么?
undefined
是未定義"類型的全局變量.尚未初始化的字段與未定義完全相等 (===).它允許程序員區分一個故意為空的值和一個簡單的未初始化的值.在 ECMAScript 5 及更高版本中,undefined
是只讀的.在此之前,其他代碼可能會修改 undefined
的值.您可以總是使用表達式 void 0
... 獲取真值 undefined
,如 myUndefinedVar = void 0;
.
Honestly, I didn't know how to make the title shorter.
I learnt how to write a jQuery plugin by studying the source of SlidesJS plugin. When I encountered something new, I just asked my good friend Google and most of the times, got a satisfactory answer. Honestly though, I never made much effort. All I know is that $
is (probably) a shorthand jQuery object constructor and that $()
and jQuery()
are the same thing provided jQuery is included.
Recently, though, I tried to understand the science behind jQuery and how to write a good jQuery plugin. I came across a very good article in which the author listed several templates for creating a jQuery plugin. Since the rest were too complex for me to understand, I liked the first one: A Lightweight Start. Now, here is the code for the said template.
/*!
* jQuery lightweight plugin boilerplate
* Original author: @ajpiano
* Further changes, comments: @addyosmani
* Licensed under the MIT license
*/
// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;(function ( $, window, document, undefined ) {
// undefined is used here as the undefined global
// variable in ECMAScript 3 and is mutable (i.e. it can
// be changed by someone else). undefined isn't really
// being passed in so we can ensure that its value is
// truly undefined. In ES5, undefined can no longer be
// modified.
// window and document are passed through as local
// variables rather than as globals, because this (slightly)
// quickens the resolution process and can be more
// efficiently minified (especially when both are
// regularly referenced in your plugin).
// Create the defaults once
var pluginName = 'defaultPluginName',
defaults = {
propertyName: "value"
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
// jQuery has an extend method that merges the
// contents of two or more objects, storing the
// result in the first object. The first object
// is generally empty because we don't want to alter
// the default options for future instances of the plugin
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
// Place initialization logic here
// You already have access to the DOM element and
// the options via the instance, e.g. this.element
// and this.options
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );
I have included the comments so as to refer to them in my questions.
I have a crude idea why window
and document
have been included in the argument of the anonymous function that wraps the plugin (I don't know what else to call it) because it is given in the comments that it sorta kinda shortens the execution time. But how does that work? Any argument of the said anonymous function wrapping the plugin gets passed on to where? And how are these addressed in the plugin?
Normally, I would do $(window).resize(function(){})
but that doesn't work in this case. If I do console.log(window)
inside the Plugin function, it says 'undefined'.
Which brings me to the other question which is: what is undefined? Isn't it a data type that is assigned to an object that isn't defined in the scope? How can it be passed as an argument? Don't the arguments have to be objects? There are a few lines written about this in the comments, but I don't understand a word of it: <so we can ensure that its value is truly undefined> whaaa?
To sum up:
- What indeed is meant by
function($)
? - Why should I include
window
,document
andundefined
as arguments offunction($)
? - If I do it, how do I access the actual
window
anddocument
objects? undefined
what, and why?
Please go easy on me. I never studied programming language as a subject for the express purpose of writing applications. I studied basic C for writing hardware oriented low-level routines for tiny core microcontrollers and that's just about it. I did learn C++ extensively and a bit of Java on my own. Just so you'd know what to expect.
When you write a function like:
(function (foo, bar) {
return foo.getElementById(bar);
})(document, "myElement")
then the function is immediately called with arguments document
and "myElement"
for parameters foo
and bar
. Therefore, inside the function, foo.getElementById(bar)
is equivalent to document.getElementById("myElement")
.
Similarly, in your plugin example, you are immediately calling the function with the arguments jQuery, document, window
.
What indeed is meant by
function($)
?
The $
simply represents a reference to a jQuery
object that is passed in to the wrapper function. Later, when the anonymous function is called with (jQuery, window, document)
, the $
reference inside the function references the jQuery
object. This is done for a number of reasons, not least of which is that $
is quicker to type. It also allows the user to apply your plugin in wrapper to a particular instance of jQuery
, produced perhaps by jQuery.noConflict()
.
Why should I include
window
,document
andundefined
as arguments offunction($)
?
You don't need to include these. The original author's reasoning is that assigning function-local variables to reference these will shorten the time it takes to resolve these variables. I assert that the savings are negligible; I personally wouldn't bother unless I used a lot of references to window
and/or document
.
As for undefined
, the original author's purpose in including this is to ensure that someone hasn't altered the undefined
global variable in EcmaScript 4 (edit: actually ECMAScript 3 -- version 4 never made it) or earlier. Again, I can't envision this problem cropping up. If you're truly worried that this could be a problem, just include something like this in your function:
if(typeof undefined !== "undefined") {
undefined = void 0;
}
If I do it, how do I access the actual
window
anddocument
objects?
All you have to do is make sure that the function call at the end of your anonymous function passes in the actual (jQuery, window, document) parameters. Or, don't include the window
and document
arguments in your function signature. Either way, you will be referring to the actual objects, regardless of the level of indirection.
undefined
what, and why?
undefined
is a global variable of type "undefined". Fields that have not been initialized are exactly equal (===) to undefined. It allows the programmer to differentiate between a deliberately null value and a simple uninitialized one. In ECMAScript 5 and later, undefined
is read only. Prior to that, it is possible that other code could modify the value of undefined
. You can always get the true value undefined
with the expression void 0
... as in myUndefinedVar = void 0;
.
這篇關于在包裝 jQuery 插件的匿名函數中使用“窗口"、“文檔"和“未定義"作為參數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!