Difference between jQuery.extend and jQuery.fn.extend?

Difference between jQuery.extend and jQuery.fn.extend?

回答1

jQuery.extend is used to extend any object with additional functions, but jQuery.fn.extend is used to extend the jQuery.fn object, which in fact adds several plugin functions in one go (instead of assigning each function separately).

jQuery.extend:

var obj = { x: function() {} }

jQuery.extend(obj, { y: function() {} });

// now obj is an object with functions x and y

jQuery.fn.extend:

jQuery.fn.extend( {
        x: function() {},
        y: function() {}
});

// creates 2 plugin functions (x and y)

 

回答2

This blog post have nice description:

$.fn.extend({
myMethod: function(){...}
});
//jQuery("div").myMethod();

$.extend({
myMethod2: function(){...}
});
//jQuery.myMethod2();

Quotes:

As a general rule, you should extend the jQuery object for functions and the jQuery.fn object for methods. A function, as opposed to a method, is not accessed directly from the DOM.

 

上一篇:What's the difference between a class and an object?


下一篇:关于laravel5.4.12新增集合操作when方法详解