如果我有如下功能:
function catchUndefinedFunctionCall( name, arguments )
{
alert( name + ' is not defined' );
}
我做了一些愚蠢的事情
foo( 'bar' );
当 foo 未定义时,有什么方法可以调用我的 catch 函数,名称为“foo”,参数为包含“bar”的数组?
如果我有如下功能:
function catchUndefinedFunctionCall( name, arguments )
{
alert( name + ' is not defined' );
}
我做了一些愚蠢的事情
foo( 'bar' );
当 foo 未定义时,有什么方法可以调用我的 catch 函数,名称为“foo”,参数为包含“bar”的数组?
无论如何,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阅读更多内容
try {
foo();
}
catch(e) {
callUndefinedFunctionCatcher(e.arguments);
}
更新
传递e.arguments
给您的函数将为您提供您最初尝试传递的内容。
someFunctionThatMayBeUndefinedIAmNotSure ? someFunctionThatMayBeUndefinedIAmNotSure() : throw new Error("Undefined function call");