简体   繁体   中英

JavaScript: is it possible to get the attempted name of an undefined function?

I've always wondered if there was a way of improving the error message one gets when attempting to use a function that doesn't exist (or that isn't a function). For example:

document.iDontExist()
TypeError: undefined is not a function

I'd like to be able to log something like:

document.iDontExist is not a function

Just to save a few seconds. I realise I have line numbers etc, I'm just wondering whether this is possible. Is there some property of the TypeError I could use to look up the name that was attempted?

No - not generally.

JavaScript doesn't "send messages" to invoke functions and any expression construct can have the () operator applied .. none of the browser engines try to "read into" the expression to report a more useful message.

A debugger (with break-on-exception) can be useful, but otherwise no - the exceptions will remain general without manual intervention.

Unfortunately not, but if this is an option for you, it could work...

Instead of calling document.iDontExist() , try:

(document.iDontExist || logError("iDontExist undefined")) && document.iDontExist();

This abuses logical operators to only call the function if it exists, and log an error (assuming logError exists!) otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM