码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScrip模块化模式写法

时间:2015-07-03 19:13:34      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

//Module 模式 闭包自包含模块
var testModule = (function(){
    var counter = 0;
    return {
        incrementCounter: function(){
            return ++counter;            
        },
        resetCounter: function(){
            console.log("counter value prior to reset: " + counter);
            counter = 0;
        }
    };
})();
testModule.incrementCounter();
testModule.incrementCounter();
testModule.resetCounter();
//包含命名空间、共有和私有变量的Module模式
var myNamespace = (function(){
    var myPrivateVar = 0;
    var myPrivateMehod = function(foo){
        console.log(foo);
    };
    return {
        myPublicVar: "foo",
        myPublicFunction: function(bar){
            myPrivateVar++;
            myPrivateMehod(bar); 
        }
    }
})();
myNamespace.myPublicFunction('hello world!');
//用模块化思想实现购物车
var basketModule = (function(){
    //私有
    var basket = [];
    function doSomethingPrivate(){
        console.log("doSomethingPrivate run");
    }
    function doSomethingElsePrivate(){
        console.log("doSomethingElsePrivate run");
    }
    //返回暴露的共有对象
    return {
        addItem: function(values){
            basket.push(values);
        },
        getItemCount: function(){
            return basket.length;
        },
        doSomething: doSomethingPrivate,
        getTotal: function(){
            var itemCount = this.getItemCount();
            total = 0;
            while(itemCount--){
                total+= basket[itemCount].price;
            }
            return total;
        },
    }
})();
basketModule.addItem({
    item: "bread",
    price: 0.5
});
basketModule.addItem({
    item: "dss",
    price: 0.5
});
console.log(basketModule.getItemCount());
console.log(basketModule.getTotal());

版权声明:本文为博主原创文章,未经博主允许不得转载。

JavaScrip模块化模式写法

标签:

原文地址:http://blog.csdn.net/waiting7436/article/details/46744693

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