简体   繁体   English

使用用户扩展jQuery插件默认选项

[英]Extending jQuery Plugin default options with user's

In the following demo: what is happening in this line of code? 在下面的演示中:这行代码中发生了什么?

settings = $.extend({}, defaultSettings, settings || {});

What is the difference between the above and this one: 上面和这个之间有什么区别:

    if(settings){
    settings = $.extend(defaultSettings, settings);
}

================================== ==================================

(function($){
    var defaultSettings = {
        mode            : 'Pencil',
        lineWidthMin    : '0',
        lineWidthMax    : '10',
        lineWidth       : '2'
    };

    $.fn.wPaint = function(settings)
    {
        settings = $.extend({}, defaultSettings, settings || {});

        return this.each(function()
        {
            var elem = $(this);

            //run some code here
        });
    }
})(jQuery);
settings = $.extend({}, defaultSettings, settings || {});

The jQuery $.extend() method copies properties from one or more objects into each other, from right to left. jQuery $ .extend()方法从右到左将一个或多个对象的属性复制到另一个对象中。 In this specific example, the method is being passed three objects: {} (empty object), defaultSettings and then settings (or an empty object if settings doesn't exist). 在此特定示例中,该方法正在传递三个对象: {} (空对象), defaultSettings然后settings (如果settings不存在,则为空对象)。 So, going from right to left, all properties of settings will be copied into defaultSettings and then the result of that will be copied into the empty object ( {} ). 因此,从右到左,设置的所有属性都将被复制到defaultSettings ,然后将其结果复制到空对象( {} )中。 The upshot of all this is that properties in settings (which are the user's custom options) will take precedence over defaultSettings and then they are all copied into an empty object. 所有这些的结果是settings中的属性(用户的自定义选项)将优先于defaultSettings ,然后它们都被复制到空对象中。 The reason for the empty object is because $.extend() actually modifies the first argument by reference, so passing in an empty object as the first object essentially makes a clone without modifying any object. 空对象的原因是因为$ .extend()实际上通过引用修改了第一个参数,所以传入一个空对象作为第一个对象实际上是在不修改任何对象的情况下进行克隆。

if(settings){
    settings = $.extend(defaultSettings, settings);
}

This does the same thing except, instead of replacing settings with an empty object if it doesn't exist, it simply doesn't execute the given code. 除了用空对象替换settings (如果它不存在)之外,它不会执行给定的代码。

UPDATE: Regarding settings || {} 更新:关于settings || {} settings || {} , this means use the settings object if it exists (technically, if it is truthy) OR use an empty object. settings || {} ,这意味着使用设置对象(如果它存在)(技术上,如果它是真实的) 使用空对象。 It avoid passing a value of undefined . 它避免传递undefined的值。

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

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