d
k
p
l
u
s

js模块编写

js模块编写

编写模块obj.js

//obj.js
'use strict';

//引入模块
const dkplus = require('dkplus.js');

!(function(){
    //模块化obj
    const obj = (function(){
        //定义属性和方法
        const name = '';
        const tech = {};
        const method = function(){}

        //暴露属性和方法
        return {
            name: name,
            tech: tech,
            method: method
        }
    })();
    //nodejs
    if (typeof exports !== 'undefined'){
        module.exports = obj;
    }
    //seajs&requirejs
    if (typeof define === 'function'){
        define(function(){
            return obj;
        });
    }
})()

使用模块obj.js,导出模块render.js

//render.js
'use strict';

const obj = require('./obj.js');

const render = (function(){
    function init() {
        //访问obj的name属性
        console.log(obj.name);
        //访问obj的method方法
        obj.method();
    }
    return {
        init
    }
});

module.exports = render;

使用模块obj.js&render.js,主运行程序index.js

//index.js
'use strict';

const obj = require('./obj.js');
const render = require('./render.js');
const jQuery = require('./jQuery.js');

require('./index.less');

$(function(){
    //访问obj的method方法
    obj.method();
    //初始化render
    render.init();
})

posted @ 2018-01-19 13:18  dkplus  阅读(229)  评论(0编辑  收藏  举报