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

时间:2010-03-26 23:36:52

标签: javascript javascript-events error-handling undefined

如果我有以下功能:

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

我做的事情很蠢像

foo( 'bar' );

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

3 个答案:

答案 0 :(得分: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)

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

答案 1 :(得分:5)

try {
 foo();
}
catch(e) {
   callUndefinedFunctionCatcher(e.arguments);
}

<强>已更新

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

答案 2 :(得分:0)

someFunctionThatMayBeUndefinedIAmNotSure ? someFunctionThatMayBeUndefinedIAmNotSure() : throw new Error("Undefined function call");