标签:
//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());
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/waiting7436/article/details/46744693