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. 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). 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 ( {}
). 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. 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.
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.
UPDATE: Regarding settings || {}
settings || {}
, this means use the settings object if it exists (technically, if it is truthy) OR use an empty object. It avoid passing a value of undefined
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.