有没有办法处理JavaScript中调用的未定义函数?

Emo*_*ory 8 javascript error-handling undefined javascript-events

如果我有如下功能:

function catchUndefinedFunctionCall( name, arguments )
{
    alert( name + ' is not defined' );
}
Run Code Online (Sandbox Code Playgroud)

而且我做的事情很傻

foo( 'bar' );
Run Code Online (Sandbox Code Playgroud)

当没有定义foo时,是否有某些方法可以调用我的catch函数,名称为'foo',参数是包含'bar'的数组?

npu*_*pup 10

无论如何,在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)
Run Code Online (Sandbox Code Playgroud)

很酷.更多信息,访问https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/NoSuchMethod


Lev*_*ith 5

try {
 foo();
}
catch(e) {
   callUndefinedFunctionCatcher(e.arguments);
}
Run Code Online (Sandbox Code Playgroud)

更新

传递e.arguments给你的函数会给你你原本想要传递的东西.

  • `arguments`不是`Error`对象的属性,它是函数的属性.在你的例子中,`e`是一个错误对象,因此`e.arguments`将是未定义的. (5认同)