js 中如何使用(function(global){…})(this)和頁面如何調用

  1. https://stackoverflow.com/questions/10314891/how-to-use-functionglobal-this
  • 簡單普通funciton

function a(){
    alert("heihei")
}

  • 存在問題

容易出現方法名混亂,希望就只拋出一個類,不把方法名直接拋出,像第三方的 js一樣。

  • GLOBAL寫法例子(方法1)

調用時不通過new創建對象,不傳任何參數例子:

(function (GLOBAL) {
    'use strict';// PS:未聲明的變量不能使用
    var Demo,

        NAME = '[demo.js] ',//特意指明可以實現直接跳轉
        P = {},
        UNDEFINED = void 0;


    /*
     * Create and return a Demo constructor.
     *
     */
   function _Demo_() {
        function Demo() {
            var x = this;
            if (!(x instanceof Demo)) return new Demo()
            x.constructor = Demo;
        }

        Demo.prototype = P;
        return Demo;
    }


    function hello() {
        return 'hello'
    }

    P.hello = P.hello2 = function () {
        return hello()
    }

    // Export
    Demo = _Demo_();
    Demo['default'] = Demo.Demo = Demo;

    //AMD.
    if (typeof define === 'function' && define.amd) {
        define(function () {
            return Demo;
        });

        // Node and other CommonJS-like environments that support module.exports.
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = Demo;

        //Browser.
    } else {
        GLOBAL.Demo = Demo;
    }
})(this);
  • 頁面調用

<script th:src="@{~/js/utils/demo.js}"></script>


  let a = Demo(0.7).hello()
            console.log(a)
  • GLOBAL寫法例子(方法2)

調用時不通過new創建對象,傳入參數例子:

(function (global) {
    'use strict';// PS:未聲明的變量不能使用
    var Demo2,

        NAME = '[dateFormat.js] ',//特意指明可以實現直接跳轉
        P = {};


    function _Demo2_() {
        function Demo2() {
            var x = this;
            if (!(x instanceof Demo2)) return new Demo2()
            x.constructor = Demo2;
        }

        Demo2.prototype = P;
        return Demo2;
    }

    // dateFormat("YYYY-mm-dd HH:MM",  new Date())
    function dateFormat(fmt, date) {
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 時
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以繼續添加,必須轉化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            }
        }
        return fmt;
    }

    P.hello = function (fmt, date) {
        return dateFormat(fmt, date);
    };


    // Export
    Demo2 = _Demo2_();
    Demo2['default'] = Demo2.Demo2 = Demo2;

    /**
     * export via AMD or CommonJS, otherwise leak a global
     */
    if (typeof define === 'function' && define.amd) {
        define(function () {
            return Demo2;
        });
    } else if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = Demo2;
    } else {
        global.Demo2 = Demo2;
    }
}(this));
  • 頁面調用

 const a = Demo2().hello("YYYY-mm-dd HH:MM",  new Date());
            console.log(a)
  • GLOBAL寫法例子(方法3-用new)

調用時通過new創建對象,傳入參數例子:

/*!
 * jsDemo2
 * https://github.com/derek-watson/jsDemo2
 *
 * Copyright 2013, Derek Watson
 * Released under the MIT license.
 *
 * Includes parseDemo2 regular expressions
 * http://blog.stevenlevithan.com/archives/parseuri
 * Copyright 2007, Steven Levithan
 * Released under the MIT license.
 */

/*globals define, module */

(function(global) {

    /**
     * Creates a new Demo2 object
     * @constructor
     */
    function Demo2() {
    }

    // dateFormat("YYYY-mm-dd HH:MM",  new Date())
    function dateFormat(fmt, date) {
        let ret;
        const opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "m+": (date.getMonth() + 1).toString(),     // 月
            "d+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 時
            "M+": date.getMinutes().toString(),         // 分
            "S+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以繼續添加,必須轉化成字符串
        };
        for (let k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            }
        }
        return fmt;
    }

    Demo2.prototype.hello = function(fmt,date) {
        return dateFormat(fmt, date);
    };


    /**
     * export via AMD or CommonJS, otherwise leak a global
     */
    if (typeof define === 'function' && define.amd) {
        define(function() {
            return Demo2;
        });
    } else if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = Demo2;
    } else {
        global.Demo2 = Demo2;
    }
}(this));
  • 頁面調用

 <script th:src="@{~/js/utils/demo2.js}"></script>


 const a = new Demo2().hello("YYYY-mm-dd HH:MM",  new Date());
            console.log(a)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章