最簡單的原生js和jquery插件封裝
最近在開發(fā)過程中用別人的插件有問題,所以研究了一下,怎么封裝自己的插件。
如果是制作jquery插件的話。就將下面的extend方法換成 $.extend 方法,其他都一樣。
總結(jié)一下實(shí)現(xiàn)原理:
將方法體封裝在一個(gè)自執(zhí)行的函數(shù)體里面,防止變量污染。
默認(rèn)參數(shù)在options設(shè)置,extend方法有由for-in遍歷得到,使得參數(shù)為用戶制定參數(shù)。
this.init是項(xiàng)目初始化,init,extend,event方法都是在demo對(duì)象的原型鏈上面的方法,方便調(diào)用。
將自己的方法直接卸載event方法里面就可以,調(diào)用參數(shù)調(diào)用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)}; // 參數(shù)合并 extend方法體在下面 this.options = this.extend({ "x": "1", "y": "2", "z": "3" }, options); this.init(); //初始化 }; demo.prototype = { init: function () { this.event(); }, // 參數(shù)合并方法體 extend: function (obj, obj2) { for (var key in obj2) { obj[key] = obj2[key]; // 確保參數(shù)唯一 } return obj }, event:function () { var _this = this; //方法調(diào)用前的回調(diào) _this.options.open&&_this.options.open(); //此處執(zhí)行方法體,使用 this.options.x\this.options.y\this.options.z進(jìn)行訪問 //打印參數(shù) console.log(this.options.x) // 方法結(jié)束的回調(diào) _this.options.close&&_this.options.close(); } } //暴露對(duì)象 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") } });

浙公網(wǎng)安備 33010602011771號(hào)