【问题标题】:Is there a way to handle undefined functions being called in JavaScript?有没有办法处理在 JavaScript 中调用的未定义函数?
【发布时间】:2011-02-01 10:02:05
【问题描述】:

如果我有如下功能:

function catchUndefinedFunctionCall( name, arguments )
{
    alert( name + ' is not defined' );
}

我做了一些愚蠢的事情

foo( 'bar' );

当 foo 未定义时,有什么方法可以调用我的 catch 函数,名称为“foo”,参数为包含“bar”的数组?

【问题讨论】:

    标签: javascript error-handling undefined


    【解决方案1】:
    someFunctionThatMayBeUndefinedIAmNotSure ? someFunctionThatMayBeUndefinedIAmNotSure() : throw new Error("Undefined function call");
    

    【讨论】:

      【解决方案2】:
      try {
       foo();
      }
      catch(e) {
         callUndefinedFunctionCatcher(e.arguments);
      }
      

      更新

      e.arguments 传递给您的函数将为您提供您最初尝试传递的内容。

      【讨论】:

      • arguments 不是Error 对象的属性,它是函数的属性。在您的示例中,e 是一个错误对象,因此 e.arguments 将是未定义的。
      • 我认为这只是检查人们想要摆脱的包罗万象的策略。
      • 我刚刚在 chrome 中运行了以下命令:try { bar('foo'); } 捕捉(e){ 警报(e.arguments); for(x in e) { alert(x) } } 它警告“foo”,然后警告“arguments”作为 e 的属性。我疯了吗?还是还是错了?
      • 在 JS 中执行 try/catch 并不总是一个好主意,特别是如果块内有异步函数。检查stackoverflow.com/questions/3677783/…
      【解决方案3】:

      无论如何,Mozilla Javascript 1.5 中有(它是非标准的)。

      看看这个:

      var myObj = {
          foo: function () {
              alert('foo!');
          }
          , __noSuchMethod__: function (id, args) {
              alert('Oh no! '+id+' is not here to take care of your parameter/s ('+args+')');
          } 
      }
      myObj.foo();
      myObj.bar('baz', 'bork'); // => Oh no! bar is not here to take care of your parameter/s (baz,bork)
      

      很酷。阅读更多https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/NoSuchMethod

      【讨论】:

      • 这很酷,几乎正是我想要的——是否有在 IE 6+ 中工作的等价物?
      • 截至 2015 年 12 月,这是一个不应再使用的过时函数。
      • @Loïc 那应该用什么?
      猜你喜欢
      • 1970-01-01
      • 2010-11-16
      • 2020-09-27
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2015-08-18
      相关资源
      最近更新 更多