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

发布于 2024-11-28 21:22:26 字数 1169 浏览 0 评论 0 原文

我刚刚开始编写 jQuery 插件。我编写了三个小插件,但我只是将这行代码复制到我的所有插件中,而实际上并不知道它的含义。有人可以告诉我更多关于这些的信息吗?也许有一天在编写框架时解释会派上用场:)

这是做什么的? (我知道它以某种方式扩展了 jQuery,但是还有什么其他有趣的事情需要了解吗)

(function($) {

})(jQuery);

以下两种编写插件的方法有什么区别:

类型 1:

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

        },

        $.fn.jPluginName.defaults = {

        }
})(jQuery);

类型 2:

(function($) {
    $.jPluginName = {

        }
})(jQuery);

<强>类型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);

我可能离这里很远,也许都意味着同样的事情。我很困惑。在某些情况下,似乎不适用于我使用类型 1 编写的插件。到目前为止,类型 3 对我来说似乎是最优雅的,但我想了解一下其他人也是如此。

I am just starting out with writing jQuery plugins. 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)

(function($) {

})(jQuery);

What is the difference between the following two ways of writing a plugin:

Type 1:

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

        },

        $.fn.jPluginName.defaults = {

        }
})(jQuery);

Type 2:

(function($) {
    $.jPluginName = {

        }
})(jQuery);

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

似梦非梦 2024-12-05 21:22:27

首先,看起来像 (function(){})() 的代码块仅仅是一个就地执行的函数。让我们把它分解一下。

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

第 2 行是一个普通函数,用括号括起来,告诉运行时将函数返回到父作用域,返回后,函数将使用第 4 行执行,也许阅读这些步骤会有所帮助,

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

您可以看到 1 是声明, 2 正在返回该函数,3 正在执行该函数。

一个如何使用它的例子。

(function(doc){

   doc.location = '/';

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

至于有关插件的其他问题:

类型 1:这实际上并不是一个插件,它是一个作为函数传递的对象,因为插件往往是函数。

类型 2:这又不是插件,因为它不扩展 $.fn 对象。它只是 jQuery 核心的扩展,尽管结果是相同的。这是如果要添加toArray等遍历函数的话。

类型3:这是添加插件的最佳方法,jQuery 的扩展原型采用一个包含您的插件名称和功能的对象,并将其添加到您的插件库中。

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. 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

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.

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.

Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.

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.

生生漫 2024-12-05 21:22:27

在最基本的层面上,(function(){...})() 形式的内容是立即执行的函数文字。这意味着您已经定义了一个函数并立即调用它。

这种形式对于信息隐藏和封装很有用,因为您在该函数内定义的任何内容对于该函数来说仍然是本地的,并且无法从外部世界访问(除非您专门公开它 - 通常通过返回的对象文字)。

这种基本形式的一个变体是您在 jQuery 插件(或一般的模块模式)中看到的。因此:

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

这意味着您正在传递对实际 jQuery 对象的引用,但它在函数文字的范围内称为 $

Type 1 并不是真正的插件。您只需将对象文字分配给 jQuery.fn 即可。通常,您将一个函数分配给 jQuery.fn,因为插件通常只是函数。

类型2与类型1类似;你并没有真正在这里创建一个插件。您只需将对象文字添加到 jQuery.fn 即可。

Type 3 是一个插件,但它不是创建插件的最佳或最简单的方法。

要了解更多相关信息,请查看类似的问题和< href="https://stackoverflow.com/questions/2421911/javascript-file-as-an-anonymous-function/2421949#2421949">答案。另外,此页面详细介绍了创作插件。

At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. 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). 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.

Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn. Typically you assign a function to jQuery.fn as plugins are usually just functions.

Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn.

Type 3 is a plugin, but it's not the best or easiest way to create one.

To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.

油饼 2024-12-05 21:22:27

一点帮助:

// 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);

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

勿挽旧人 2024-12-05 21:22:27

只是对解释的一点补充

这个结构 (function() {})(); 称为 IIFE(立即调用函数表达式),当解释器到达这一行时,它将立即执行。因此,当您编写这些行时:

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

这意味着解释器将立即调用该函数,并将 jQuery 作为参数传递,该参数将在函数内部用作 $代码>.

Just small addition to explanation

This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. 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 $.

草莓酥 2024-12-05 21:22:27

实际上,这个例子帮助我理解了 (function($) {})(jQuery); 的含义。

考虑一下:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

现在考虑一下:

  • jQuery 是一个保存 jQuery 对象的变量。
  • $ 是一个变量
    名称与其他任何名称(a$ba$b 等)一样,并且没有任何
    像 PHP 中的特殊含义。

知道我们可以再看一下我们的例子:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

Consider this:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

And now consider this:

  • jQuery is a variable holding jQuery object.
  • $ is a variable
    name like any other (a, $b, a$b etc.) and it doesn't have any
    special meaning like in PHP.

Knowing that we can take another look at our example:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4
赴月观长安 2024-12-05 21:22:27

类型 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);

我不确定为什么有人会使用扩展而不是直接在 jQuery 原型中设置属性,它只是在更多操作和更多混乱中做同样的事情。

Type 3, in order to work would have to look like this:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文