有没有办法处理在JavaScript中调用未定义的函数?
如果我有像下面这样的函数:有没有办法处理在JavaScript中调用未定义的函数?
function catchUndefinedFunctionCall(name, arguments)
{
alert(name + ' is not defined');
}
我真的很喜欢
foo('bar');
没有定义富时一些愚蠢的,是有一些方法可以让我有打电话给我的捕捉功能,名字是'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
someFunctionThatMayBeUndefinedIAmNotSure ? someFunctionThatMayBeUndefinedIAmNotSure() : throw new Error("Undefined function call");
try {
foo();
}
catch(e) {
callUndefinedFunctionCatcher(e.arguments);
}
修订
传递e.arguments
你的功能会给你你想本来通过什么。
'arguments'不是'Error'对象的属性,它是函数的一个属性。在你的例子中'e'是一个错误对象,所以'e.arguments'将会是未定义的。 – 2010-03-27 00:07:27
我认为这只是检查人们想要摆脱的全面策略。 – npup 2010-03-27 01:37:25
我刚刚在Chrome中运行以下代码: 尝试bar('foo'); (e){ alert(e.arguments); } 它提醒'foo',然后警告'参数'作为e的一个属性。我疯了吗?或者还是错了? – 2010-03-27 04:24:02
这是非常酷,几乎正是我所期待的 - 有没有相当于IE 6+的作品? – Emory 2010-04-02 17:05:36
截至2015年12月,这是一个不应该再使用的过时功能。 – 2015-12-20 13:48:50