Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将try-catch块应用于模块实例(对象)私有方法?_Javascript_Module_Try Catch_Requirejs - Fatal编程技术网

Javascript 如何将try-catch块应用于模块实例(对象)私有方法?

Javascript 如何将try-catch块应用于模块实例(对象)私有方法?,javascript,module,try-catch,requirejs,Javascript,Module,Try Catch,Requirejs,我正在使用requireJS模块研究JavaScript体系结构。 模块定义非常简单: define([ "dependency1.js", "dependency2.js" ], function (dep1, dep2) { dep1.dropdown = new Module("dropdown", function (sandbox) { // Private functions function getWhatever() {

我正在使用requireJS模块研究JavaScript体系结构。 模块定义非常简单:

define([
    "dependency1.js",
    "dependency2.js"
], function (dep1, dep2) {

    dep1.dropdown = new Module("dropdown", function (sandbox) {
      // Private functions
      function getWhatever() {
        // do something
      }

      function getAnother() {
        // do another thing
      }

      // Public methods
      return {
         doSomething: function () {
            // do one more thing
            getAnother();
         }
      };
    });
});
然后,我有一个名为“Module”的类,在该类中,我尝试将try-catch块应用于模块方法,如下所示:

var Module = function (id, creator) {
  var instance,
      sandbox = buildSandbox(),
      name,
      method;

  instance = creator(sandbox);

  for (name in instance) {
    // Looping though all methods inside module instance
    method = instance[name];

    if (typeof method === "function") {
        // Making every function execute within try catch block
        instance[name] = (function (name, method) {
           return function () {
             try { return method.apply(this, arguments); }
             catch (ex) { console.log("ERROR", name + "(): " + ex.message); }
           };
        })(name, method);
    }
  }
}
问题在于,由于模块实例只持有公共方法,所以我无法将try-catch块应用于私有方法

我在想,如果我公开所有实例方法,它将不再安全


有没有一种方法可以将try-catch块也应用于私有方法,而不必重新设计每个模块本身?

除非您想在模块内部添加代码以自动添加try-catch,否则没有方法

您基本上有两种选择:

  • 将您希望在try-catch中包含的所有方法公开,然后使用您拥有的代码
  • 别担心。如果你的公共方法最终调用了你的私有方法,那么不管怎样,你都能得到相当好的错误覆盖率
    我不会让“安全”影响你的决定。您正在编写JavaScript,人们可以随时查看源代码并查看发生的情况,这永远不会是真正安全的。

    请注意第2点:这是真的,我的公共方法现在正在调用private one-and-try-catch错误。另外,根据您将基础与核心和模块分离的方法,我在基础内部构建了一个AJAX管理器。在AJAX管理器中,我添加了另一个try-catch来捕获可能来自AJAX回调的错误:log(1,“回调中的问题:”+ex.message,url)。看来我已经被它覆盖了。