使用'window','document'和'undefined'作为包装jQuery插件的匿名函数中的参数 [英] Using 'window', 'document' and 'undefined' as arguments in anonymous function that wraps a jQuery plugin

查看:144
本文介绍了使用'window','document'和'undefined'作为包装jQuery插件的匿名函数中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

老实说,我不知道如何缩短标题。

Honestly, I didn't know how to make the title shorter.

我通过研究 SlidesJS 插件。当我遇到新的东西时,我只是问了我的好朋友 Google ,并且大部分时间都得到了满意的答案。老实说,我从来没有做过多少努力。我所知道的是 $ 是(可能)一个简写的jQuery对象构造函数,而 $() jQuery()提供jQuery是一回事。

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.

最近,我试图理解jQuery背后的科学和如何编写一个好的 jQuery插件。我遇到了一个非常好的文章,其中作者列出了几个用于创建jQuery插件的模板。由于其余部分太复杂,我无法理解,我喜欢第一个:轻量级开始。现在,这是所述模板的代码。

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.

我有一个简单的想法,为什么 window 文件已包含在参数中包装插件的匿名函数(我不知道还有什么叫它)因为它在注释中给出了它有点缩短了执行时间。但是这有什么作用呢?包装插件的所述匿名函数的任何参数都传递到哪里?如何在插件中解决这些问题?

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?

通常,我会做 $(窗口).resize(function(){})但在这种情况下不起作用。如果我在插件函数中执行 console.log(window),则会显示未定义。

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'.

哪个带来我对另一个问题是:什么是未定义?是不是数据类型分配给范围内未定义的对象?怎么能作为一个论点传递?参数不必是对象吗?在评论中有一些关于这一点的内容,但是我不明白它的一个词:< 所以我们可以确保它的值真正未定义> whaaa?

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?

总结:


  • 函数究竟是什么意思($ )

  • 我为什么要包含窗口文件 undefined 作为函数的参数($)

  • 如果我这样做,如何访问实际的窗口文档对象?

  • undefined 什么,为什么?

  • 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?

请放轻松我。我从未将编程语言作为编写应用程序的明确目的而学习。我研究了基本的C,用于为微型核心微控制器编写面向硬件的低级例程,而这就是它。我确实学习了很多C ++,并且自己学习了一些Java。只是这样你才知道会发生什么。

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.

推荐答案

当你编写如下函数时:

(function (foo, bar) {
    return foo.getElementById(bar);
})(document, "myElement")

然后立即调用函数 document myElement参数 foo bar 。因此,在函数内部, foo.getElementById(bar)等同于 document.getElementById(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").

同样,在你的插件示例中,你立即使用参数 jQuery,document,window 调用该函数。

Similarly, in your plugin example, you are immediately calling the function with the arguments jQuery, document, window.


函数究竟是什么意思($)

$ 只是表示对 jQuery的引用传递给包装函数的对象。稍后,当使用(jQuery,window,document)调用匿名函数时,函数引用中的 $ 引用 jQuery 对象。这样做有很多原因,其中最重要的是 $ 可以更快地输入。它还允许用户将包装器中的插件应用于 jQuery 特定实例,可能由 jQuery.noConflict生成()

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().


为什么要包含窗口 document undefined 作为函数的参数($)

您不需要来包含这些内容。原作者的推理是,分配函数局部变量来引用它们将缩短解决这些变量所需的时间。我断言节省的费用可以忽略不计;除非我使用很多窗口的引用和/或文档

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.

至于 undefined ,原作者包含此内容的目的是确保某人没有改变了EcmaScript 4中的 undefined 全局变量(编辑:实际上是ECMAScript 3 - 版本4从未成功)或更早。再次,我无法想象这个问题出现了。如果你真的担心这可能是一个问题,只需在你的函数中包含这样的东西:

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;
}




如果我这样做,我该如何访问实际的窗口文件对象?

您所要做的就是确保匿名函数末尾的函数调用传入实际(jQuery,window,document)参数。或者,不要在函数签名中包含窗口文档参数。无论哪种方式,无论间接级别如何,您都将引用实际对象。

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 什么,为什么?

undefined 是undefined类型的全局变量。尚未初始化的字段与undefined完全相同(===)。它允许程序员区分故意空值和简单的未初始化值。在ECMAScript 5及更高版本中, undefined 是只读的。在此之前,其他代码可能会修改 undefined 的值。您可以始终使用表达式 void 0 ...获取真实值 undefined myUndefinedVar = void 0;

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;.

这篇关于使用'window','document'和'undefined'作为包装jQuery插件的匿名函数中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆