如何确定函数是否为空

编程入门 行业动态 更新时间:2024-10-19 22:28:20
本文介绍了如何确定函数是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我希望能够检查给定的功能是否为空。也就是说,它的主体没有任何东西,例如:

I want to be able to check whether a given function is empty or not. That is, there is nothing in its body, eg:

function foo() {} function iAmEmpty(a) { // yep, empty }

随着一些初步的游戏,我有一些我认为可能没问题的东西,使用 toString()和一些正则表达式。

With some initial playing around, I've got something which I think might be ok, by using toString() and some regexes.

function foo(a, b, c) {} /^function[^{]+\{\s*\}/m.test(foo.toString()); // true function bar(a, b, c) { var d; } /^function[^{]+\{\s*\}/m.test(bar.toString()); // false

我只是想知道是否有更好的方法?您可以看到以上问题吗?

I was just wondering if there was a better approach? Are there any problems with the above you can see?

推荐答案

这是不可取的。没有标准确切地确定函数的 toString()方法应该返回什么,所以即使你在当前的浏览器中使用它,未来的浏览器也可以合理地改变它们的实现并打破你的代码。

This isn't advisable. There is no standard determining precisely what a function's toString() method should return, so even if you get this working in current browsers, future browsers may justifiably change their implementation and break your code.

Kangax简要介绍了这一点: perfectionkills/those-tricky-functions/

Kangax has written briefly about this: perfectionkills/those-tricky-functions/

更多推荐

如何确定函数是否为空

本文发布于:2023-11-29 17:13:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647054.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!