首页 > jQuery插件开发-为什么要用extend()方法?

jQuery插件开发-为什么要用extend()方法?

我知道jQuery插件开发中有一种是extend,是合并对象用的。
为什么要用jQuery.extend() 的方法扩展jQuery方法?
而不是直接用jQuery.pluginname = function(){} 这样的方法?
在我看来这两种都是直接在jQuery命名空间下加一个方法,那为什么更推荐使用extend方法来扩展??


先回答你的问题:
jQuery.extend({pluginname: function() {}})和jQuery.pluginname = function() {}没有什么区别,都是去扩展了jQuery本身,也就是$对象,只是前者会在定义多个plugin时方便点:

// without jQuery.extend()
jQuery.pluginA = function() {};
jQuery.pluginB = function() {};
jQuery.pluginC = function() {};

// with jQuery.extend()
jQuery.extend({
    pluginA: function() {},
    pluginB: function() {},
    pluginC: function() {}
});

其实这个和模拟类时怎样扩展prototype是一样的:

// 有人这么写
function ClassA() {}
ClassA.prototype.funcA = function() {};
ClassB.prototype.funcB = function() {};

// 也有人这么写
function ClassB() {}
ClassB.prototype = {
    constructor: ClassB,
    funcA: function() {},
    funcB: function() {}
};

更多参考:

怎样创建jQuery plugin
https://learn.jquery.com/plugins/basic-plugin-creation/

$.extend和$.fn.extend的区别
http://www.cnblogs.com/wang_yb/archive/2014/11/17/4103137.html

【热门文章】
【热门文章】