做什么(function($){})(jQuery); 意思?

本文翻译自:What does (function($) {})(jQuery); mean?

I am just starting out with writing jQuery plugins. 我只是开始编写jQuery插件。 I wrote three small plugins but I have been simply copying the line into all my plugins without actually knowing what it means. 我写了三个小插件,但是我只是简单地将该行复制到我所有的插件中,而实际上并不知道这意味着什么。 Can someone tell me a little more about these? 有人可以告诉我更多有关这些的信息吗? Perhaps an explanation will come in handy someday when writing a framework :) 也许有一天写一个框架时会有用的解释:)

What does this do? 这是做什么的? (I know it extends jQuery somehow but is there anything else interesting to know about this) (我知道它以某种方式扩展了jQuery,但对此还有其他有趣的信息)

(function($) {

})(jQuery);

What is the difference between the following two ways of writing a plugin: 以下两种编写插件的方式有什么区别:

Type 1: 类型1:

(function($) {
    $.fn.jPluginName = {

        },

        $.fn.jPluginName.defaults = {

        }
})(jQuery);

Type 2: 类型2:

(function($) {
    $.jPluginName = {

        }
})(jQuery);

Type 3: 类型3:

(function($){

    //Attach this new method to jQuery
    $.fn.extend({ 

        var defaults = {  
        }  

        var options =  $.extend(defaults, options);  

        //This is where you write your plugin's name
        pluginname: function() {

            //Iterate over the current set of matched elements
            return this.each(function() {

                //code to be inserted here

            });
        }
    }); 
})(jQuery);

I could be way off here and maybe all mean the same thing. 我可能离这里很远,也许所有的意思都一样。 I am confused. 我很困惑。 In some cases, this doesn't seem to be working in a plugin that I was writing using Type 1. So far, Type 3 seems the most elegant to me but I'd like to know about the others as well. 在某些情况下, 似乎不适用于我使用Type 1编写的插件。到目前为止,Type 3对我来说似乎是最优雅的,但我也想了解其他类型。


#1楼

参考:https://stackoom.com/question/ck6D/做什么-function-jQuery-意思


#2楼

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. 首先,看起来像(function(){})()的代码块仅仅是就地执行的功能。 Let's break it down a little. 让我们分解一下。

1. (
2.    function(){}
3. )
4. ()

Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help 第2行是一个普通函数,用括号括起来,告诉运行时将函数返回到父作用域,一旦返回,则使用第4行执行该函数,也许通读这些步骤会有所帮助

1. function(){ .. }
2. (1)
3. 2()

You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function. 您可以看到1是声明,2是返回函数,3只是执行函数。

An example of how it would be used. 有关如何使用它的示例。

(function(doc){

   doc.location = '/';

})(document);//This is passed into the function above

As for the other questions about the plugins: 至于关于插件的其他问题:

Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions. 类型1:这实际上不是插件,而是作为函数传递的对象,因为插件往往是函数。

Type 2: This is again not a plugin as it does not extend the $.fn object. 类型2:再次不是插件,因为它没有扩展$.fn对象。 It's just an extenstion of the jQuery core, although the outcome is the same. 尽管结果是相同的,但这只是jQuery核心的扩展。 This is if you want to add traversing functions such as toArray and so on. 这是如果要添加遍历函数,例如toArray等。

Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you. 类型3:这是添加插件的最佳方法,jQuery的扩展原型采用一个对象来保存您的插件名称和功能,并将其添加到您的插件库中。


#3楼

Type 3, in order to work would have to look like this: 类型3,为了工作,必须看起来像这样:

(function($){
    //Attach this new method to jQuery
    $.fn.extend({     
        //This is where you write your plugin's name
        'pluginname': function(_options) {
            // Put defaults inline, no need for another variable...
            var options =  $.extend({
                'defaults': "go here..."
            }, _options);

            //Iterate over the current set of matched elements
            return this.each(function() {

                //code to be inserted here

            });
        }
    }); 
})(jQuery);

I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter. 我不确定为什么有人会直接在jQuery原型中设置扩展属性,而只是在更多的操作和更多的混乱中才做同样的事情。


#4楼

At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. 在最基本的级别上, (function(){...})()是立即执行的函数文字。 What this means is that you have defined a function and you are calling it immediately. 这意味着您已经定义了一个函数并且正在立即调用它。

This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal). 这种形式对于信息的隐藏和封装很有用,因为您在函数内部定义的任何内容都保留在该函数的本地且无法从外界访问(除非您专门公开了它-通常通过返回的对象文字)。

A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). 您在jQuery插件中(或通常在此模块模式中)看到的是这种基本形式的变体。 Hence: 因此:

(function($) {
  ...
})(jQuery);

Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal. 这意味着您要传递对实际jQuery对象的引用,但在函数文字范围内,它称为$

Type 1 isn't really a plugin. 类型1并不是真正的插件。 You're simply assigning an object literal to jQuery.fn . 您只需将对象文字分配给jQuery.fn Typically you assign a function to jQuery.fn as plugins are usually just functions. 通常,您为jQuery.fn分配一个函数,因为插件通常只是函数。

Type 2 is similar to Type 1; 类型2与类型1相似; you aren't really creating a plugin here. 您并不是在这里真正创建插件。 You're simply adding an object literal to jQuery.fn . 您只需在jQuery.fn添加对象文字。

Type 3 is a plugin, but it's not the best or easiest way to create one. Type 3是一个插件,但这不是创建一个的最佳或最简单的方法。

To understand more about this, take a look at this similar question and answer . 要了解更多关于这一点,看看这个类似的问题答案 Also, this page goes into some detail about authoring plugins. 此外, 此页面还将详细介绍创作插件。


#5楼

A little help: 一点帮助:

 // an anonymous function (function () { console.log('allo') }); // a self invoked anonymous function (function () { console.log('allo') })(); // a self invoked anonymous function with a parameter called "$" var jQuery = 'I\\'m not jQuery.'; (function ($) { console.log($) })(jQuery); 


#6楼

Just small addition to explanation 只是解释的一小部分

This structure (function() {})(); 此结构(function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. 称为IIFE (立即调用函数表达式),当解释器到达此行时,它将立即执行。 So when you're writing these rows: 因此,当您编写这些行时:

(function($) {
  // do something
})(jQuery);

this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $ . 这意味着,解释器将立即调用该函数,并将jQuery作为参数传递,它将在函数内部用作$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值