如何确定函数是否为空 [英] How to determine if a function is empty

查看:80
本文介绍了如何确定函数是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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简要介绍了这一点: http://perfectionkills.com/those-tricky-functions/

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

这篇关于如何确定函数是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆