如何扩展插件的 原型 中的公共方法?
例如,我有一个插件中的 method1 方法,并且我想通过其 .prototype
添加另一个或更多方法。这是否可行?
var extensionMethods = {
method2: function(){
return this;
}
};
$.fn.MyPlugin.prototype = extensionMethods;
console.log($(".element").MyPlugin());
结果,
Object { Element={...}, Options={...}, method1=function()}
理想情况下,
Object { Element={...}, Options={...}, method1=function(), method2=function(), method2function()}
我的插件样板文件
(function ($) {
// Create the plugin name and defaults once
var pluginName = 'MyPlugin';
// Attach the plugin to jQuery namespace.
$.fn[pluginName] = function(PublicOptions) {
// Set private defaults.
var Defaults = {
param1: 'param1',
param2: 'param2',
onSuccess: function(){}
};
// Do a deep copy of the options.
var Options = $.extend(true, {}, Defaults, PublicOptions);
// Define a functional object to hold the api.
var PluginApi = function(Element, Options) {
this.Element = Element;
this.Options = Options;
};
// Define the public api and its public methods.
PluginApi.prototype = {
method1: function(PublicOptions) {
// Process the options.
var Options = $.extend(true, {}, this.Options, PublicOptions);
return this.Options;
}
};
//Create a new object of api.
return new PluginApi(this, Options);
};
})(jQuery);
有什么想法吗?
$(".element").MyPlugin()
对象来访问PluginApi.prototype
,因为PluginApi
构造函数是在IIFE内部定义的。但这当然不是很好的做法。 - dfsq$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
不太好。 - Run$
提供上下文,因此插件不会在其他使用$
的页面上中断。 - charlietfl