第一种方法:
在很多基于jQuery或基于Zepto的插件中,在立即函数执行前面会加上";"这个符号。
这是为了防止前面的其他插件没有正常关闭。
在立即执行函数执行时,会一般会传入jQuery,window等。举个例子:
;(function($,window,undefined){
//.....
})(jQuery,window)
window传递进来作为局部变量存在,而非全局变量,这样可以加快解析流程,以及影响最小化。
undefined没有传进来,以便可以确保此undefined是真正的undefined。因为ECMAScript3里的undefined是可以修改的,ECMAScript5不可以修改。
下面是自定义jQuery插件的规范:
;(function($,window,undefined){
var pluginName = "chaojidan",
defaults = {
name:"dandan"
};
function Plugin(element, options){
this.element = element;
this.options = $.extend( {} , defaults,options );
this._name = pluginName;
this._defaults = defaults;
this.init();
}
Plugin.prototype.init = function(){
//初始化插件
};
$.fn[pluginName] = function(options){ //真正的插件包装,防止出现多个实例
return this.each(function(){
if(!$.data(this,"plugin_"+pluginName)){
$.data(this,"plugin_"+pluginName, new Plugin(this, options));
}
});
} })(jQuery,window)
调用此插件:
$("#elem").chaojidan({name:"xiaoxiao"});
第二种方法:
;(function($,window,undefined){
var myObject = {
init : function(options, elem){
this.options = $.extend({}, this.options, options);
this.elem = elem;
this.$elem = $(elem);
this._build();
return this;
},
options:{
name:"dandan"
},
_build:function(){ },
myMethod:function(){ }
};
if(typeof Object.create != "function"){
Object.create = function(o){
function F(){}
F.prototype = o;
return new F();
}
}
$.plugin = function(name, object){
$.fn[name] = function(options){
return this.each(function(){
if(!$.data(this,name)){
$.data(this,name,Object.create(object).init(options,this))
}
});
}
}
$.plugin("chaojidan",myObject);
})(jQuery,window);
调用方式:
$("#elem").chaojidan({name:"xiaoxiao"});
对于上面的两种方法,我们定义插件时,都传递了带有默认值的对象字面量给$.extend()。然而,如果我们想自定义此默认值的对象字面量,也就是说,用户可以重写此默认对象字面量,那么我们该如何来写呢?
其实非常简单,我们只要把此默认对象字面量这样赋值就行了。
$.fn.pluginName.options = {
name:"dandan"
}
这样,用户能够重写全局默认配置,达到插件构造的灵活性。
加油!