1

我试图了解如何通过 javascript 中的文件分解功能。我试图将命名空间视为单例类。我不明白为什么在下面的代码中MODULE_A.privateMethod1()会抛出错误:Uncaught TypeError: undefined is not a function. 当我打开记录的对象时,我也看不到那里的私有方法。

索引.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Test Project</title>

    <script src="index.js"></script>
    <script src="moduleA.js"></script>
  </head>
    <body>
      <div>
        hi
      </div>
  </body>
</html>

index.js:

(function() {

  var initializeWindow = function() {
    console.log("initializeWindow");
    MODULE_A.publicMethod1();
  };

  window.addEventListener('load', initializeWindow);
})();

模块A.js:

// "Singleton Class"
var MODULE_A = (function() {
  // ---------------------------------------------------------------------------
  // "Private" Class Constants
  // ---------------------------------------------------------------------------
  var A_CONSTANT_NUMBER = 1;

  // ---------------------------------------------------------------------------
  // "Private" Class Variables (Properties)
  // ---------------------------------------------------------------------------
  var myPrivateVar_ = 2;

  // ---------------------------------------------------------------------------
  // "Private" Methods
  // ---------------------------------------------------------------------------
  var privateMethod1 = function() {
    console.log("A.privateMethod1");
  };

  var privateMethod2 = function() {
    console.log("A.privateMethod2");
  };

  return {
    // ---------------------------------------------------------------------------
    // "Public" Class Variables (Properties)
    // ---------------------------------------------------------------------------
    aPublicVar1: 3,

    // ---------------------------------------------------------------------------
    // "Public" Methods
    // ---------------------------------------------------------------------------
    publicMethod1: function() {
      console.log("A.publicMethod1");
      this.publicMethod2();
      // ERROR HERE!!!
      this.privateMethod1();
      this.privateMethod2();
    },

    publicMethod2: function() {
      console.log("A.publicMethod2");
    }
  }
})();

在此处输入图像描述

4

1 回答 1

3

解决方案是以下两种之一:

当你用 声明某些东西时var,它不能被访问this

任何一个 :

this.privateMethod1 = function() {
console.log("A.privateMethod1");
};

或者

 publicMethod1: function() {
  console.log("B.publicMethod1");
  this.publicMethod2();
  privateMethod1();
  privateMethod2();
},

编辑:如果您希望该方法为私有,则应遵循方法2,您可以访问此站点以获取更多说明。

于 2014-10-01T01:29:51.047 回答