Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to handle undefined functions being called in JavaScript?

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'?

like image 982
Emory Avatar asked Mar 26 '10 23:03

Emory


People also ask

How do you handle undefined exceptions in JavaScript?

You can use the typeof to determine the type of the unevaluated operand. It will return the type of operand in a string. You can use "===", if you know they are equal value and equal type.

How does JavaScript handle undefined data?

myVariable is declared and not yet assigned with a value. Accessing the variable evaluates to undefined . An efficient approach to solve the troubles of uninitialized variables is whenever possible assign an initial value. The less the variable exists in an uninitialized state, the better.

How do you handle undefined and null in JavaScript?

The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. Note: We cannot use the typeof operator for null as it returns object .


2 Answers

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

like image 88
npup Avatar answered Oct 15 '22 00:10

npup


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

UPDATED

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

like image 31
Levi Hackwith Avatar answered Oct 14 '22 23:10

Levi Hackwith