Kirill Vorobjov
Kirill Vorobjov

Reputation: 87

Search for function name ( Javascript )

Good day,

Is there any alternative to arguments.callee.toString().match to find a function name ? Like make another function with a loop that will search for the name.

All my functions are named :

function mthdSearch() {
    console.log("test0")
};

function funkA() {
    console.log("test1");
}


function funkB() {
    console.log("test2");
}

Upvotes: 2

Views: 536

Answers (1)

FK82
FK82

Reputation: 5075

As stated in my comment, this is impossible from a general perspective.

You can construct a counter example by declaring functions locally (i.e. within local scope) of another function and then try to access the declared functions by name outside of the scope of that function:

(function() {
	function f() {console.log("f")}
 	var g = function g() {console.log("g");};
 	h = function h() {console.log("h");};
  f();
  g();
  h();
})();

try {f();}
catch(e) {console.log(e.message);}

try {g();}
catch(e) {console.log(e.message);}

try {h();}
catch(e) {console.log(e.message);}

As you can see, only h is accessible outside of the scope of the anonymous function, because it was declared globally (by omitting the var keyword).


If you're looking for a technique to store a collection of functions and access them by name, use an object oriented JavaScript pattern (MDN introduction to object oriented JavaScript).

Upvotes: 1

Related Questions