简体   繁体   English

JavaScript:是否可以获取未定义函数的尝试名称?

[英]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? 我可以使用TypeError某些属性来查找尝试的名称吗?

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. JavaScript不会“发送消息”来调用函数,并且任何表达式构造都可以应用()运算符..没有一个浏览器引擎会尝试“读入”表达式以报告更有用的消息。

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() ,请尝试:

(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. 这会滥用逻辑运算符,仅在函数存在时调用该函数,否则会记录一个错误(假设存在logError !)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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