码迷,mamicode.com
首页 > Web开发 > 详细

webpack模块定义和使用的模式

时间:2017-07-08 21:11:51      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:技术   span   image   ddc   single   一个   思考   str   count()   

在使用webpack作为模块加载工具时,我在想module.exports的模块应该是一种什么模式,最直接地思考是单例。不太确定,所以写一个简单例子做测试。

测试代码

singleton.js:

var Singleton = {
    count: 0,
    addCount: function(){
        Singleton.count++;
    }
}
 
console.log(‘Singleton 输出‘);
module.exports = Singleton;

App.vue:

import Singleton from ‘./js/singleton‘
 
export default {
    ……
    created(){
        Singleton.addCount();
        console.log(‘App.vue count:‘, Singleton.count);
    }
} 

Hello.vue:

import Singleton from ‘../js/singleton‘
 
export default {
    ……
    created(){
        Singleton.addCount();
        console.log(‘Hello.vue count:‘, Singleton.count);
    }
}

输出

技术分享总结

从例子可以看出,使用模块的方式是单例(就是exports出来的对象),而编写的方式是模块模式(在我设计模式文章有写)。

模块模式的好处在于你可以暴露你想要的属性和方法(私有的隐藏),甚至做一些初始化操作。

PS:注意模块定义和使用该模块的模式区分

webpack模块定义和使用的模式

标签:技术   span   image   ddc   single   一个   思考   str   count()   

原文地址:http://www.cnblogs.com/lovesong/p/7137902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!