发现 exports 和 module.exports 的关系,貌似找到暴露代码的新方法

这两东西都是指向 this 对象的!
exports===this
而且
module.exports===this

对外暴露接口的新方法:直接绑定到 this 对象上即可?

这是我今天鼓捣 webpack 的时候发现的,特此记录。
本项目链接 git@gitee.com:zhaiduting/webpk.git
或者用 gitee.com/zhaiduting/webpk.git
项目下载后
1、安装依赖包 npm install
2、编译项目 npx webpack
3、在浏览器中打开 dist/index.html
4、按下功能键 F12 即可看到如下截图
file
其中主js文件为 main.js 代码如下

var thisModule=require('./thisModule')
console.log('in main.js:')
console.log(thisModule);
console.log('thisModule.af(7,8):'+thisModule.af(7,8));
console.log('thisModule.f(9):'+thisModule.f(9));

其中引入的模块为 thisModule.js 代码如下

var a = 200;

module.exports.f = [1,2,3];                 // module.exports 指向不变
exports.f = a;                              // exports 指向不变,覆盖了同名属性!

console.log('module.exports:');
console.log(module.exports)                 // 200
console.log('\n')

console.log('exports:');
console.log(exports)                        // 200
console.log('\n')

console.log('module.exports===exports:')
console.log(module.exports===exports)       // true
console.log('\n')

console.log('module.exports===this')
console.log(module.exports===this)          // true
console.log('\n')

console.log('exports===this')
console.log(exports===this)                 // true
console.log('\n')

this.arr=[2019, 3, 18]                      // Export Array OK
this.obj={email: 'zhaiduting@163.com'}      // Export Object OK
this.f=function(f){return f}                // Export Function OK
this.af=(a, f)=>a+f                         // Export Arrow Function OK

各版本号如下
file

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 1

我在18号的文章里记录了【挂载this对象对外暴露代码】的方法,但是在某些环境里此法失效了,原因是 this 对象为空。不仅 this 失效,就连 exports 和 module.exports 也一并失效!必须采用 export {} 之类的写法才能对外暴露代码。

今天,我又发现了新的、可谓怪异的对外暴露代码的写法!此法可以突破封锁,已在 Vue 项目里面测试成功。

//导出代码的正规写法
module.exports.a = [1,2,3];                 // module.exports 指向不变
exports.a = 200;                            // exports 指向不变,覆盖了同名属性!

//挂载 this 导出代码的写法如下
this.arr=[2019, 3, 24]                      // Export Array OK
this.obj={email: 'zhaiduting@163.com'}      // Export Object OK
this.f=function(f){return f}                // Export Function OK
this.af=(a, f)=>a+f                         // Export Arrow Function OK

//另类怪异的导出写法【还可以跟 export {} 混用】
Object.assign(arguments[0].exports, {
    foo: 'foo',                             // Export String OK
    bar:(msg)=>msg,                         // Export Arrow Function OK
})

项目的下载链接依然是 https://gitee.com/zhaiduting/webpk.git 为什么要用这种怪异的写法?这个链接里写了说明 博客:暴露代码的怪异写法 arguments [0].exports 应用一例

file

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
63
粉丝
17
喜欢
140
收藏
118
排名:132
访问:7.4 万
私信
所有博文
社区赞助商