我什么时候应该在jQuery中使用$.fn.extend()

When should I use $.fn.extend() in jQuery?

本文关键字:fn extend 什么时候 jQuery      更新时间:2024-05-22

我是jQuery的新手。一些jQuery插件使用$.fn.extend(),我在jQueryapi文档中看到过,但我不知道什么时候应该使用它,也不知道如何使用它。

我在插件滑板车滑块中看到过它的使用。我真的很想知道如何使用它。

如果有人能帮助我,我将不胜感激。提前谢谢你。

我什么时候使用它以及如何使用

当您想要合并对象时。例如,您有

var A = {
   foo: 42
};

var B = {
   bar: 21;
};

现在您想要将B合并到A中,以创建

var A = {
   foo: 42,
   bar: 21
};

这是由完成的

$.extend(A, B);

例如,如果您有任何带有配置的插件,您可以设置其默认值,并用$.extend 进行补充

看看这个:

(function ($) {
    $.superPlugin = {
        // plugin defaults
        defaults: 
        {
            mainClass: 'node',
            orientation: 'vertical',
            focusEvent: function (event) {
                console.log('Focus!');
            }
        };
    };
    // plugin code
    $.fn.superPlugin = function (fn, options) {
        var config = $.extend( true, {}, $.setSelect.defaults, options );
        /**
         *  results: { 
         *      mainClass: 'node', 
         *      orientation: 'horizontal', 
         *      focusEvent: function (event) {
         *         console.log('Custom focus event!');
         *      }
         *  }
         */
    };
})(jQuery);
// custom config
var options = {
    orientation: 'horizontal',
    focusEvent: function (event) {
        console.log('Custom focus event!')
    }
}
// bind plugin to element
$('.item').superPlugin(options);