当前位置:网站首页>(function(global,factory){
(function(global,factory){
2022-07-28 13:28:00 【前端切图仔Zz】
在如此多的Javascript库中,我看到global 、factory作为函数的参数,这是为什么呢?
答:
这是UMD模式,你可以很清晰的通过下图看到看到这段代码在你的库中做了什么:
┌──────────────────┐ ┌──────────────────┐
│ ▼ ▼ │
│ (function (global, factory) {
│
│ │
│ │
│ /* deleted for clarity */ │
│ ┌───────────────────────────┘
│ │
│ }(this, function () {
'use strict';
│ │
└───────┘
/* */
})
所以这根本上是一个立即执行函数,如果你把匿名函数改写为有名字的函数你可以更清晰的看到这段代码的结构。
// rename function () { 'use strict' ...
function Vue () {
'use strict';
/* */
}
// rename function (global, factory) ...
function UMD (global, factory) {
/* deleted for clarity */
}
UMD(this, Vue);
global根本上就是当从函数外部引用时指向全局对象(浏览器的window和node.js没命名),factory是创建库对象的函数,根本上factory是vue,jq等三方库的完成。
用这样的方式来写这个结构,没有创建任何不必要的全局变量和函数,因此避免了污染全局区域并且避免了与其他库变量或函数名的冲突。
至于为什么要把this分派给global,这是因为window是一个完全没有保护的全局变量(这是为什么node.js没有给它起名字)并且任何第三放库都可以重写或者修改它。如果你在使用不知名的第三方库时想要浏览器的原始全局对象,你需要使用this这个小技巧。
边栏推荐
- 如何有效进行回顾会议(上)?
- 【Utils】FastDFS工具类
- 线程阻塞的三种情况。
- 什么是自旋锁 自旋锁是指当一个线程尝试获取某个锁时,如果该锁已被其他线程占用,就一直循环检测锁是否被释放,而不是进入线程挂起或睡眠状态。 /** * 为什么用自旋锁:多个线程对同一个变量
- 分集技术简略
- How to write test cases in software testing technology
- 【Util】redis工具类:把redis的value序列化器修改为GenericJackson2JsonRedisSerializer,就支持返回值为对象或集合了
- [try to hack] hfish honeypot deployment
- 修订版 | 目标检测:速度和准确性比较(Faster R-CNN,R-FCN,SSD,FPN,RetinaNet和YOLOv3)...
- Development and definition of software testing
猜你喜欢
随机推荐
On websocket
[ecmascript6] class
webSocket聊天
[ecmascript6] proxy and reflection
MySQL development skills - View
Mobile phone scrolling screenshot software recommendation
Target detection: speed and accuracy comparison (fater r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)
How does vos3000 send incoming calls to okcc
每日一题——奖学金
Super resolution reconstruction based on deep learning
How to write test cases in software testing technology
How did Dongguan Huawei cloud data center become a new model of green data center?
【LeetCode】1331. 数组序号转换
Multithreading and high concurrency (III) -- source code analysis AQS principle
【Try to Hack】HFish蜜罐部署
Solve the problem that uniapp wechat applet canvas cannot introduce fonts
目标检测:速度和准确性比较(Fater R-CNN,R-FCN,SSD,FPN,RetinaNet和YOLOv3)
jenkins
VOS3000如何呼入送到OKCC
Diablo 4 ps4/ps5 beta has been added to the Playstation database








