在不少基于jQuery或基于Zepto的插件中,在当即函数执行前面会加上";"这个符号。javascript
这是为了防止前面的其余插件没有正常关闭。java
在当即执行函数执行时,会通常会传入jQuery,window等。举个例子:函数
;(function($,window,undefined){ //..... })(jQuery,window)
window传递进来做为局部变量存在,而非全局变量,这样能够加快解析流程,以及影响最小化。ui
undefined没有传进来,以即可以确保此undefined是真正的undefined。由于ECMAScript3里的undefined是能够修改的,ECMAScript5不能够修改。this
下面是自定义jQuery插件的规范:prototype
;(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);
调用方式:blog
$("#elem").chaojidan({name:"xiaoxiao"}); ip
对于上面的两种方法,咱们定义插件时,都传递了带有默认值的对象字面量给$.extend()。然而,若是咱们想自定义此默认值的对象字面量,也就是说,用户能够重写此默认对象字面量,那么咱们该如何来写呢?
其实很是简单,咱们只要把此默认对象字面量这样赋值就好了。
$.fn.pluginName.options = {
name:"dandan"
}
这样,用户可以重写全局默认配置,达到插件构造的灵活性。
加油!