1.組件封裝一般單獨寫在一個js文件里
2.整個插件寫在一個立即執行函數里;就是function(){}();函數自執行;保證里面的變量不會與外界互相影響
function(win,doc,$,undefined){
}(window,document,jQuery)
或者寫在一個閉包里
(function(){
}())
3.定義構造函數
//插件名,調用的時候直接new一下插件名就行了並傳參數或者傳對象
(function(window, undefined) {
//一般習慣將這個構造函數名手寫字母大寫
var Star = function(id){ // function Star(doc){}
// this的指向為調用的實例;我們此時姑且認為this就指向這個函數;因為這樣我們之后再想獲取這個btn就可以直接用this.btn了;
而不是在document.getElementById(....)
this.btn = document.getElementByTagName("button");
this.btn = document.getElementById(id);
//你也可以定義一些默認的參數
this.author = "iamlhr";
//執行下你下面寫的函數;如果整個插件沒有執行函數;一堆方法function就不調用;這里是調用的時候最開始執行的函數
this.init();
}
Star.prototype = {
init: function(){ //調用下面寫的函數
this.otherMethod()
},
otherMethod: function(){}
};
}(window));
4.創建實例
<html>
<div id=“main”></div>
<div id="myShaoe"></div>
</html>
<script>
new Star("main"); //這里是實例1調用插件的代碼
new Star("myShape"); //這里是實例2調用插件的代碼
</script>
5.插件封裝完成