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

来源:互联网 发布:浪潮税控开票软件 编辑:程序博客网 时间:2024/05/04 15:34
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();            });
原创粉丝点击