Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a function is empty

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
}

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?

like image 310
nickf Avatar asked Sep 06 '25 06:09

nickf


1 Answers

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 has written briefly about this: http://perfectionkills.com/those-tricky-functions/

like image 137
Tim Down Avatar answered Sep 08 '25 19:09

Tim Down