最近在開發過程中用別人的插件有問題,所以研究了一下,怎么封裝自己的插件。
如果是制作jquery插件的話。就將下面的extend方法換成 $.extend 方法,其他都一樣。
總結一下實現原理:
將方法體封裝在一個自執行的函數體里面,防止變量污染。
默認參數在options設置,extend方法有由for-in遍歷得到,使得參數為用戶制定參數。
this.init是項目初始化,init,extend,event方法都是在demo對象的原型鏈上面的方法,方便調用。
將自己的方法直接卸載event方法里面就可以,調用參數調用this.options.x 就可以使用。
下列代碼封裝成js,引入,如何使用方法在下面.
(function () { 'use strict'; var demo = function (options) { //demo("options") 或者 new demo("options")都可以使用demo方法 if(!(this instanceof demo)){return new demo(options)}; // 參數合並 extend方法體在下面 this.options = this.extend({ "x": "1", "y": "2", "z": "3" }, options); this.init(); //初始化 }; demo.prototype = { init: function () { this.event(); }, // 參數合並方法體 extend: function (obj, obj2) { for (var key in obj2) { obj[key] = obj2[key]; // 確保參數唯一 } return obj }, event:function () { var _this = this; //方法調用前的回調 _this.options.open&&_this.options.open(); //此處執行方法體,使用 this.options.x\this.options.y\this.options.z進行訪問 //打印參數 console.log(this.options.x) // 方法結束的回調 _this.options.close&&_this.options.close(); } } //暴露對象 window.demo = demo; }());
// 使用方法 demo("args") 和 new demo("args") demo({ "x": "111", "y": "3", "c":"ccc", open:function () { console.log("start") }, close:function () { console.log("end") } });