Javascript模块模式的变体

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript模块模式的变体相关的知识,希望对你有一定的参考价值。

  1. var myModule = function () {
  2.  
  3. var publicObj = {}; // returnable object...
  4.  
  5. var privateProperty = "I can be accessed only from within this module";
  6. var privateMethod = function () {
  7. // has access to public properties as publicObj.publicVar and private methods
  8. }
  9.  
  10. var publicObj.publicProperty = "Publicly accessible as myModule.publicVar.";
  11. var publicObj.publicMethod = function () {
  12. // Publicly accessible as myModule.publicMethod
  13. }
  14.  
  15. return publicObj;
  16.  
  17. }();
  18.  
  19.  
  20. var myModule = function(){
  21.  
  22. var privateMethod = function(){
  23. publicMethod();
  24. }
  25.  
  26. var publicMethod = function(){
  27. return this;
  28. }
  29.  
  30. // Copy over methods you want to be public
  31. return {
  32. publicMethod : publicMethod
  33. }
  34.  
  35. }();
  36.  
  37.  
  38. var myModule = function(){
  39.  
  40. // Persists in privateMethods due to closure
  41. var that = {};
  42.  
  43. function privateMethod(){
  44. that.publicMethod();
  45. }
  46.  
  47. return {
  48. publicProperty: true,
  49. publicMethod: function(){},
  50. // Make this visible in private scope
  51. init: function(){
  52. that = this;
  53. }
  54. };
  55.  
  56. }().init();

以上是关于Javascript模块模式的变体的主要内容,如果未能解决你的问题,请参考以下文章

构造器模式与模块模式

模块化 JavaScript - 除了 CommonJS 和 AMD 之外,还有啥方法可以考虑吗?

246 JavaScript严格模式

JavaScript学习(七十二)—严格模式

NodeJS基础

[笔记]《JavaScript高级程序设计》- 事件