简体   繁体   English

编写jQuery插件 - 多个实例化

[英]Writing jQuery plugin — multiple instantiation

I have a question regarding the local variables for my jQuery plugin. 我有一个关于我的jQuery插件的局部变量的问题。 I am pretty sure if I declare them outside the main jQuery function register, then every time the plugin is called it will redefine the variables. 我很确定如果我在主jQuery函数寄存器之外声明它们,那么每次调用插件时它都会重新定义变量。

Example: 例:

(function($){
    jQuery.fn.test = function(options){
        if ( options ) { 
            $.extend( settings, options );
          }
        this.each(function(i,item){
            // do whatever i am going to do
        });

    };


    var settings = {
        value1: "hello",
        value2: "word"
    };
})(jQuery);

Say that $(object).test({value1:'newterm'}); 假设$(object).test({value1:'newterm'}); is called multiple times.. Am I correct in thinking that every time that method is called, that it will override the settings with the most recently declared settings? 被多次调用..我是否正确地认为每次调用该方法时,它都会覆盖最近声明的设置的设置?

If i want multiple instances of my plugin, do I need to declare everything within the scope of the main jQuery.fn.test = function(){//here} method? 如果我想要我的插件的多个实例,我是否需要在主jQuery.fn.test = function(){//here}方法的范围内声明所有内容?

Yes, that is correct, because $.extend will modify settings which is in the closure scope exposed when the jQuery initialization function sets up .test on the global object jQuery. 是的,这是正确的,因为$.extend将修改settings这是暴露在封闭范围时,jQuery的初始化函数设置.test在全局对象jQuery的。 That closure scope is the same everytime you execute .test ; 每次执行时,关闭范围都是相同的.test ; therefore, all objects will retain changes. 因此,所有对象都将保留更改。

It depends on the order you pass objects to $.extend. 它取决于您将对象传递给$ .extend的顺序。 The first (target) object passed will be modified, in your case the settings object. 传递的第一个(目标)对象将被修改,在您的情况下是设置对象。 If you want to keep the defaults: 如果要保留默认值:

$.extend(options, settings);

Or to get a brand new object: 或者获得一个全新的对象:

var newoptions = $.extend({}, options, settings);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM