js模块开发(同步模块)实现原理

const F = {};
//定义模块管理器
F.define = function (str, fn) {
    var parts = str.split('.'),
        old = parent = this,
        i = len = 0;
    if (parts[0] === 'F') {
        parts = parts.slice();
    }
    if (parts[0] === 'define' || parts[0] === 'modules') {
        return;
    }
    for (len = parts.length; i < len; i++) {
        if (typeof parent[parts[i]] === 'undefined') {
            parent[parts[i]] = {};
        }
        old = parent;
        parent = parent[parts[i]];
    }
    if (fn) {
        old[parts[--i]] = fn();
    }
    return this;
}
//模块调用方法
F.module = function () {
    var args = Array.from(arguments),
        fn = args.pop(),
        parts = args[0] && args[0] instanceof Array ? args[0] : args,
        modules = [],
        modIDs = '',
        i = 0,
        ilen = parts.length,
        parent, j, jlen;
    while (i < ilen) {
        if (typeof parts[i] === 'string') {
            parent = this;
            modIDs = parts[i].replace(/^F./, '').split('.');
            for (j = 0; j < modIDs.length; j++) {
                parent = parent[modIDs[j]] || false;
            }
            modules.push(parent);
        } else {
            modules.push(parts[i]);
        }
        i++;
    }
    fn.apply(null, modules);
}
定义人和动物模版
F.define('person', function () {
            return {
                sayHello: function () {
                    alert('hello');
                }
            }
        });
F.define('animal', function () {
            return {
                sayWang: function () {
                    alert('wang wang');
                }
            }
        });
引入模版,并调用定义的模版方法
F.module(['man', 'animal'], function (man, dog) {
                man.sayHello();
                dog.sayWang();
            });

你可能感兴趣的:(复习大纲)