怎樣寫一個js插件


js插件的形式有很多種,這里我分享一個自己比較熟識的,ES5語法,先預覽,再講解

;(function(global) {
    "use strict";
    var MyPlugin = function(options) {

    };

    MyPlugin.prototype = {
        init: function() {

        }
    };

    if (typeof module !== 'undefined' && module.exports) module.exports = MyPlugin;
    if (typeof define === 'function') define(function() { return MyPlugin; });
    global.MyPlugin = MyPlugin;

})(this);

 

這種寫法用於創建一個類,雖然ES5沒有真正意思上的類,只能用function模擬,我們也暫且稱之為類,ES6有class關鍵字,這里不作詳述。如上代碼兼容CommonJs/AMD/CMD規范,較為通用。注解如下:

//;分號開頭,用於防止代碼壓縮合並時與其它代碼混在一起造成語法錯誤
//而事實證明,uglify壓縮工具會將無意義的前置分號去掉,我只是習慣了這么寫

//(function(){})();立即執行函數,閉包,避免污染全局變量
//通常一個插件只暴露一個變量給全局供其它程序調用
//還有其它寫法,運算符+函數體+括號
//例:!function(){}(); +function(){}(); -function(){}();
//    void function(){}(); 等等只要能對函數返回值進行運算的符號都可以
;(function(global) {

    //開啟嚴格模式,規范代碼,提高瀏覽器運行效率
    "use strict";

    //定義一個類,通常首字母大寫
    var MyPlugin = function(options) {

    };

    //覆寫原型鏈,給繼承者提供方法
    MyPlugin.prototype = {
        init: function() {

        }
    };

    //兼容CommonJs規范
    if (typeof module !== 'undefined' && module.exports) module.exports = MyPlugin;

    //兼容AMD/CMD規范
    if (typeof define === 'function') define(function() { return MyPlugin; });

    //注冊全局變量,兼容直接使用script標簽引入該插件
    global.MyPlugin = MyPlugin;

//this,在瀏覽器環境指window,在nodejs環境指global
//使用this而不直接用window/global是為了兼容瀏覽器端和服務端
//將this傳進函數體,使全局變量變為局部變量,可縮短函數訪問全局變量的時間
})(this);

 

接下來動手開發一個可以修改div背景顏色的插件

  • modify_div_bg.js
;(function(global) {
    "use strict";
    var M = function(el) {
        this.el = typeof el === "string" ? document.querySelector(el) : el;
    };

    M.prototype = {
        setBg: function(bg) {
            this.el.style.background = bg;
        }
    };

    if (typeof module !== 'undefined' && module.exports) module.exports = M;
    if (typeof define === 'function') define(function() { return M; });
    global.ModifyDivBg = M;

})(this);

 

  • index.html
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>怎樣寫一個js插件</title>
    <script src="./modify_div_bg.js"></script>
</head>
<body>
    <div id="div">怎樣寫一個js插件</div>
    <script>
    var mObj = new ModifyDivBg("#div");
    mObj.setBg("#f00");
    </script>
</body>
</html>

 

將modify_div_bg.js和index.html的代碼放到同一個目錄,用Chrome瀏覽器打開index.html就可以看到效果了。打開調試控制台(windows按F12,Mac按option+command+i),在Console里輸入mObj.setBg("#ff0");回車,將會修改div背景顏色。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM