pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

在包裝 jQuery 插件的匿名函數中使用“窗口"

Using #39;window#39;, #39;document#39; and #39;undefined#39; as arguments in anonymous function that wraps a jQuery plugin(在包裝 jQuery 插件的匿名函數中使用“窗口、“文檔和“未定義作為參數) - IT屋-程序員軟件
本文介紹了在包裝 jQuery 插件的匿名函數中使用“窗口"、“文檔"和“未定義"作為參數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

老實說,我不知道如何縮短標題.

我通過研究 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, 窗口, 文檔);

我已將評論包括在內,以便在我的問題中引用它們.

我有一個粗略的想法,為什么 windowdocument 被包含在包裝插件的匿名函數的參數中(我不知道是什么否則調用它) 因為它在評論中給出它有點縮短執行時間.但這是如何工作的?包裝插件的上述匿名函數的任何參數都會傳遞到哪里?這些在插件中是如何解決的?

通常,我會這樣做 $(window).resize(function(){}) 但在這種情況下不起作用.如果我在插件函數中執行 console.log(window),它會顯示未定義".

這讓我想到另一個問題:undefined 是什么?不是分配給未在范圍內定義的對象數據類型嗎?它如何作為參數傳遞?論點不是必須是對象嗎?評論中寫了幾行關于此的內容,但我一個字都看不懂:<所以我們可以確保它的值是真正未定義的> whaaa?

總結一下:

  • function($)究竟是什么意思?
  • 為什么要在 function($) 的參數中包含 windowdocumentundefined?李>
  • 如果這樣做,如何訪問實際的 windowdocument 對象?
  • 未定義什么,為什么?
<小時>

請對我放輕松.我從來沒有為了編寫應用程序的明確目的而將編程語言作為一門學科.我學習了基本的 C 語言,用于為微型核心微控制器編寫面向硬件的低級例程,僅此而已.我確實廣泛地學習了 C++ 和一點點 Java.只是為了讓您知道會發生什么.

解決方案

當你寫這樣的函數時:

(function (foo, bar) {返回 foo.getElementById(bar);})(文檔,我的元素")

然后立即使用參數 document"myElement" 為參數 foobar 調用該函數.因此,在函數內部,foo.getElementById(bar)等價于document.getElementById("myElement").

同樣,在您的插件示例中,您會立即使用參數 jQuery, document, window 調用該函數.

<塊引用>

function($)究竟是什么意思?

$ 僅表示對傳遞給包裝函數的 jQuery 對象的引用.稍后,當使用 (jQuery, window, document) 調用匿名函數時,函數內部的 $ 引用引用了 jQuery 對象.這樣做的原因有很多,其中最重要的是 $ 可以更快地鍵入.它還允許用戶將包裝器中的插件應用到 jQuery特定實例,可能由 jQuery.noConflict() 生成.p><塊引用>

我為什么要包含 windowdocumentundefined 作為 function($) 的參數?p>

您不需要包含這些.原作者的推理是分配函數局部變量來引用這些將縮短解析這些變量所需的時間.我斷言節省的費用微不足道;除非我使用 大量window 和/或 document 的引用,否則我個人不會打擾.

至于 undefined,原作者包含此內容的目的是確保有人沒有更改 EcmaScript 4 中的 undefined 全局變量(實際上是 ECMAScript 3-- 版本 4 從未成功)或更早版本.同樣,我無法想象會出現這個問題.如果你真的擔心這可能是一個問題,只需在你的函數中包含這樣的內容:

if(typeof undefined !== "undefined") {未定義=無效0;}

<塊引用>

如果我這樣做,我如何訪問實際的 windowdocument 對象?

您所要做的就是確保匿名函數末尾的函數調用傳入實際的(jQuery、窗口、文檔)參數.或者,不要在函數簽名中包含 windowdocument 參數.無論哪種方式,您都將引用 實際 對象,而不管間接級別如何.

<塊引用>

未定義什么,為什么?

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 and undefined as arguments of function($)?
  • If I do it, how do I access the actual window and document 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 and undefined as arguments of function($)?

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 and document 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模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

jQuery/JavaScript Library for avatar creation?(用于創建頭像的 jQuery/JavaScript 庫?)
How to do following mask input problem?(如何做以下掩碼輸入問題?)
Issues Setting Value/Label Using DropKick Javascript(使用 DropKick Javascript 設置值/標簽的問題)
how to unit-test private methods in jquery plugins?(如何對 jquery 插件中的私有方法進行單元測試?)
stellar.js - configuring offsets / aligning elements for a vertical scrolling website?(stellar.js - 為垂直滾動網站配置偏移量/對齊元素?)
jQuery masked input plugin. select all content when textbox receives focus(jQuery 屏蔽輸入插件.當文本框獲得焦點時選擇所有內容)
主站蜘蛛池模板: 扬子叉车厂家_升降平台_电动搬运车|堆高车-扬子仓储叉车官网 | 安徽免检低氮锅炉_合肥燃油锅炉_安徽蒸汽发生器_合肥燃气锅炉-合肥扬诺锅炉有限公司 | COD分析仪|氨氮分析仪|总磷分析仪|总氮分析仪-圣湖Greatlake | 焦作网 WWW.JZRB.COM | 背压阀|减压器|不锈钢减压器|减压阀|卫生级背压阀|单向阀|背压阀厂家-上海沃原自控阀门有限公司 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | 铝镁锰板厂家_进口钛锌板_铝镁锰波浪板_铝镁锰墙面板_铝镁锰屋面-杭州军晟金属建筑材料 | 细砂提取机,隔膜板框泥浆污泥压滤机,螺旋洗砂机设备,轮式洗砂机械,机制砂,圆锥颚式反击式破碎机,振动筛,滚筒筛,喂料机- 上海重睿环保设备有限公司 | 100_150_200_250_300_350_400公斤压力空气压缩机-舰艇航天配套厂家 | 上海物流公司,上海货运公司,上海物流专线-优骐物流公司 | 济南玻璃安装_济南玻璃门_济南感应门_济南玻璃隔断_济南玻璃门维修_济南镜片安装_济南肯德基门_济南高隔间-济南凯轩鹏宇玻璃有限公司 | 春腾云财 - 为企业提供专业财税咨询、代理记账服务 | 超细粉碎机|超微气流磨|气流分级机|粉体改性设备|超微粉碎设备-山东埃尔派粉碎机厂家 | 阴离子_阳离子聚丙烯酰胺厂家_聚合氯化铝价格_水处理絮凝剂_巩义市江源净水材料有限公司 | 整车VOC采样环境舱-甲醛VOC预处理舱-多舱法VOC检测环境仓-上海科绿特科技仪器有限公司 | 洛阳永磁工业大吊扇研发生产-工厂通风降温解决方案提供商-中实洛阳环境科技有限公司 | 小型气象站_车载气象站_便携气象站-山东风途物联网 | 酵素生产厂家_酵素OEM_酵素加盟_酵素ODM_酵素原料厂家_厦门益力康 | 河南中整光饰机械有限公司-抛光机,去毛刺抛光机,精密镜面抛光机,全自动抛光机械设备 | 出国劳务公司_正规派遣公司[严海] | 天长市晶耀仪表有限公司| (中山|佛山|江门)环氧地坪漆,停车场地板漆,车库地板漆,聚氨酯地板漆-中山永旺地坪漆厂家 | 电竞馆加盟,沈阳网吧加盟费用选择嘉棋电竞_售后服务一体化 | 杜康白酒加盟_杜康酒代理_杜康酒招商加盟官网_杜康酒厂加盟总代理—杜康酒神全国运营中心 | 电磁铁_推拉电磁铁_机械手电磁吸盘电磁铁厂家-广州思德隆电子公司 | 仓储货架_南京货架_钢制托盘_仓储笼_隔离网_环球零件盒_诺力液压车_货架-南京一品仓储设备制造公司 | 校园文化空间设计-数字化|中医文化空间设计-党建|法治廉政主题文化空间施工-山东锐尚文化传播公司 | 防弹玻璃厂家_防爆炸玻璃_电磁屏蔽玻璃-四川大硅特玻科技有限公司 | 合肥汽车充电桩_安徽充电桩_电动交流充电桩厂家_安徽科帝新能源科技有限公司 | 武汉宣传片制作-视频拍摄-企业宣传片公司-武汉红年影视 | 股票入门基础知识_股票知识_股票投资大师_格雷厄姆网 | 活性炭-果壳木质煤质柱状粉状蜂窝活性炭厂家价格多少钱 | 大倾角皮带机-皮带输送机-螺旋输送机-矿用皮带输送机价格厂家-河南坤威机械 | 喷砂机厂家_自动喷砂机生产_新瑞自动化喷砂除锈设备 | 烟气在线监测系统_烟气在线监测仪_扬尘检测仪_空气质量监测站「山东风途物联网」 | 标策网-专注公司商业知识服务、助力企业发展 | 阿尔法-MDR2000无转子硫化仪-STM566 SATRA拉力试验机-青岛阿尔法仪器有限公司 | 自动焊锡机_点胶机_螺丝机-锐驰机器人 | 冷藏车-东风吸污车-纯电动环卫车-污水净化车-应急特勤保障车-程力专汽厂家-程力专用汽车股份有限公司销售二十一分公司 | 背压阀|减压器|不锈钢减压器|减压阀|卫生级背压阀|单向阀|背压阀厂家-上海沃原自控阀门有限公司 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | 大连海岛旅游网>>大连旅游,大连海岛游,旅游景点攻略,海岛旅游官网 | PVC地板|PVC塑胶地板|PVC地板厂家|地板胶|防静电地板-无锡腾方装饰材料有限公司-咨询热线:4008-798-128 |