js外掛的經典寫法與總結
阿新 • • 發佈:2019-01-28
之前寫了一篇關於js外掛的方法,可以傳入引數,當時不能夠拓展方法,而且模式也不是很好,雖然能夠滿足一定的業務要求。下面是對js外掛的完善,可以實現引數傳入,方法拓展,鏈式操作,設計模式更加清晰。
<!DOCTYPE html> <html> <head> <title>js外掛測試</title> <script type="text/javascript" src="./jquery.js"></script> </head> <body> <div style="width:200px;height:200px;border:1px solid;background:red" class="mydiv">測試</div> <script type="text/javascript"> (function($){ //定義在閉包函式中的全域性變數,用來初始化引數,其他的所有函式可以呼叫 var config; //一些私有函式,相當於php類中private的私有方法,被主函式呼叫 var privateFunction = function(){ // 執行程式碼 console.log(arguments[0]); } //主函式包含在method中,對外暴露,可以被jquery的例項物件執行 var methods = { //初始化的函式,傳入引數物件 init: function(options){ // 在每個元素上執行方法,同時返回該jqueryded的例項物件 // console.log(options); return this.each(function() { var $this = $(this); // console.log($this); // 嘗試去獲取settings,如果不存在,則返回“undefined” var settings = $this.data('pluginName'); // console.log(settings); // 如果獲取settings失敗,則根據options和default建立它 if(typeof(settings) == 'undefined'){ var defaults = { name:'zengbing', sex:'nan', onSomeEvent: function() {} }; settings = $.extend({}, defaults, options); // 儲存我們新建立的settings $this.data('pluginName',settings); }else{ // 如果我們獲取了settings,則將它和options進行合併(這不是必須的,你可以選擇不這樣做) settings = $.extend({}, settings, options); // 如果你想每次都儲存options,可以新增下面程式碼: $this.data('pluginName', settings); } //將該配置引數賦值全域性變數,方便其他函式呼叫 config=settings; // 執行私有的方法,完成相關邏輯任務 // privateFunction(config.name); }); }, //銷燬快取的變數 destroy: function(options) { // 在每個元素中執行程式碼 return $(this).each(function() { var $this = $(this); // 執行程式碼 // 刪除元素對應的資料 $this.removeData('pluginName'); }); }, //其他的主題函式。可以完成物件的其他操作 val: function(options1,options2,options3) { // 這裡的程式碼通過.eq(0)來獲取選擇器中的第一個元素的,我們或獲取它的HTML內容作為我們的返回值 var someValue = this.eq(0).html(); // 返回值 console.log(arguments); return someValue; }, getContent: function(){ return this.each(function(){ var content=$(this).text(); console.log(content); //獲取全域性變數的初始化的值 console.log(config.sex) }); } }; $.fn.pluginName = function(){ var method = arguments[0]; if(methods[method]) { method = methods[method]; //將含有length屬性的陣列獲取從第下標為1的之後的陣列元素,並返回陣列 arguments = Array.prototype.slice.call(arguments,1); }else if( typeof(method) == 'object' || !method ){ method = methods.init; }else{ $.error( 'Method ' + method + ' does not exist on jQuery.pluginName' ); return this; } //jquery的例項物件將擁有執行method的能力,method的this是指jquery的例項物件 return method.apply(this,arguments); } })(jQuery); //用法例項 var config={ name:'huang', sex:'nv' }; //先初始化引數配置,在執行各個主體函式,函式中可以呼叫config的變數,其實就是jquery的鏈式操作 $('div.mydiv').pluginName(config).pluginName('getContent').pluginName('val','bing'); </script> </body> </html>