Several methods of using closure package to customize module in JS

Source: Internet
Author: User

1. Custom modules:

JS file with a specific function

Encapsulates all the data and functions inside a function

Exposes an object or function that contains n methods only outward

Module users only need to implement the corresponding function by invoking the method of the object exposed by the module.

1. Using the function method to self-invoke

/** * Created by Lonecloud on 2017/9/10. */(function (window) {    var debug= "DEBUG"    /**     * Print log     * @param args */    function log (args        ) { Console.log (args)    }    /**     * Debug using closures     * @param args *    /function debug (args) {        Console.log (Debug+args);    }    /**     * Write     * @param args     *    /function write (args) {        document.write (args)    }    window.$ = {        Log:log,        write:write,        debug:debug    }) (window);//Call $.write ("DDA") $.debug ("DSDs") $.log (" DSQWD ")

2. Modular after function declaration

/** * Created by Lonecloud on 2017/9/10. */function Common (window) {    var debug = "Debug"    /**     * Print log     * @param args     *    /function log (args) {        console.log (args)    }    /**     * Debug using closures     * @param args *     /    function debug (args) {        console.log (debug + args);    }    /**     * Write     * @param args     *    /function write (args) {        document.write (args)    }    return {        Log:log,        debug:debug,        write:write    }}//call var common=common (window); Common.log ("121") Common.debug (12232) common.write ("DADSA")

Several methods of using closure package to customize module in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.