js中模块化编程思想

今天碰到一个题目:
如果你是一个熟悉模块化打包工具的前端开发者。不考虑使用如require.js等这些已经实现的工具。要求用原生的方法实现,如何引入三个模块,即三个js文件,比如a.js ,b.js和c.js。要求同时引入,然后在执行相应的回调函数。
思路:模块化思想的核心

小怪兽爱吃肉
浏览 547回答 2
2回答

冉冉说

根据上面那位兄得的答案,顺手写了一下,可能不正确,never mind就写两个子模块吧,原理应该是一样的main.jsvar opt1 = {&nbsp; type: 'GET',&nbsp; url: './1.js',&nbsp; headers: {&nbsp; &nbsp; "Content-Type": "text/plain"&nbsp; },&nbsp; dataType: "script"}var opt2 = {&nbsp; type: 'GET',&nbsp; url: './2.js',&nbsp; headers: {&nbsp; &nbsp; "Content-Type": "text/plain"&nbsp; },&nbsp; dataType: "script"}var pro1 = ajax(opt1)var pro2 = ajax(opt2)Promise.all([pro1, pro2]).then(function(result) {&nbsp; for(var i = 0, len = result.length; i < len; i ++) {&nbsp; &nbsp; eval(result[i])&nbsp; }&nbsp; this.mod1 = mod1})function ajax(options) {&nbsp; options = options || {};&nbsp; options.type = (options.type || "GET").toUpperCase();&nbsp; options.async = (options.async == false) ? false : true;&nbsp; options.dataType = options.dataType || "json";&nbsp; //form-data上传文件可以用{}覆盖默认设置&nbsp; options.headers = options.headers || { "Content-Type": "application/json" };&nbsp; var xhr = _createXHR();&nbsp; var isPost = options.type == 'POST';&nbsp; return new Promise(function (resolve, reject) {&nbsp; &nbsp; xhr.onreadystatechange = function () {&nbsp; &nbsp; &nbsp; if (xhr.readyState == 4) {&nbsp; &nbsp; &nbsp; &nbsp; if (xhr.status == 200) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; resolve((options.dataType == 'json') ? JSON.parse(xhr.responseText) : xhr.responseText);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reject(xhr.status);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; xhr.open(options.type.toUpperCase(), isPost ? options.url : encodeURI(options.url), options.async);&nbsp; &nbsp; for (var key in options.headers) {&nbsp; &nbsp; &nbsp; xhr.setRequestHeader(key, options.headers[key]);&nbsp; &nbsp; }&nbsp; &nbsp; xhr.send(isPost ? options.data : null);&nbsp; });&nbsp; function _createXHR() {&nbsp; &nbsp; if (window.XMLHttpRequest) {&nbsp; &nbsp; &nbsp; return new XMLHttpRequest();&nbsp; &nbsp; }&nbsp; &nbsp; else if (window.ActiveXObject) {&nbsp; &nbsp; &nbsp; return new ActiveXObject('Microsoft.XMLHTTP');&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; alert('Your browser does not support Ajax');&nbsp; &nbsp; }&nbsp; }}1.jsvar mod1 = {&nbsp; say: function (it) {&nbsp; &nbsp; console.log(it)&nbsp; }}2.jsvar mod2 = {&nbsp; bark: function () {&nbsp; &nbsp; alert('wong wong')&nbsp; }}然后放在浏览器里面执行:暂时只想到把模块里的对象放到window上面变全局变量这个方法至于你说的会向服务器发请求,我觉得一般主模块和子模块都是放在同个服务器上面的,就算主模块要发起请求加载子模块,也是相当于服务器本地加载js文件而已,没什么大问题仅供参考。刚看了看Promise.all是按顺序同步发出请求,在这里说明一下免得误导,不过都是异步操作,按顺序发出请求也不会相互阻塞

慕的地6264312

ajax请求js文件后用wrapper包起来eval,我猜是这样。另外你可以看看node.js的解决方法,把其中的读文件部分换成发请求应该就行了,但模块的解析策略上可能会稍有变动。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript