Is there a way to handle undefined functions being

2019-04-26 18:09发布

If I have a function like the following:

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

and I do something silly like

foo( 'bar' );

when foo isn't defined, is there some way I can have my catch function called, with name being 'foo' and arguments being an array containing 'bar'?

3条回答
干净又极端
2楼-- · 2019-04-26 18:55
someFunctionThatMayBeUndefinedIAmNotSure ? someFunctionThatMayBeUndefinedIAmNotSure() : throw new Error("Undefined function call");
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-26 19:01

There is in Mozilla Javascript 1.5 anyway (it's nonstandard).

Check this out:

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)

Pretty cool. Read more at https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/NoSuchMethod

查看更多
狗以群分
4楼-- · 2019-04-26 19:03
try {
 foo();
}
catch(e) {
   callUndefinedFunctionCatcher(e.arguments);
}

UPDATED

passing e.arguments to your function will give you what you tried to pass originally.

查看更多
登录 后发表回答