I have a function from an object, lets say Object.MyFunc. I need to send this function name into another function like so: doSomething("Object.MyFunc");
any advise?
I have a function from an object, lets say Object.MyFunc. I need to send this function name into another function like so: doSomething("Object.MyFunc");
any advise?
If you are trying to call MyFunc
from within doSomething
, you can just pass the actual function:
var someObject = new Object();
someObject.MyFunc = function() { alert('test'); }
function doSomething(func) {
func();
}
doSomething(someObject.MyFunc);
There isn't a really good way to get the function name. In JavaScript, you can have anonymous functions and therefore don't have a decent way to name them.
In any case, you might have some luck using arguments.callee.toSring()
. For example:
function foo() {
alert("I am " + arguments.callee.toString());
}
But, this is poor because not all functions have names and some browsers may append implementation-specific details to this string.
But, perhaps you are trying to do something else besides getting the name? If you want to eventually call the function, you can actually pass the function itself. This is called a lambda function. For example:
function foo(inFunc) {
inFunc();
}
foo(function() { alert("foo"); });
The above code creates an anonymous function that pops up an alert. It is then passed to the foo
function which just calls whatever function is passed into it.
If you have this function:
function test()
{
alert('here');
}
You can call it in this way:
function testTest(func)
{
func();
}
testTest(test);
As others have pointed out, it is most likely that whatever you're trying to do can be done better a different way. However, if you truly need to find the name of a function, there is one fairly simple way to do this, but it will not work in all cases.
//returns the name of the function func on the object obj
function getFuncName(obj, func){
for(var funcName in obj){
if(obj[funcName] === func){
return funcName;
}
}
}
alert(getFuncName(Object, Object.MyFunc)); //alerts "MyFunc"
The limitation here, is that you'll need both the object and the function, and the function will have to be iterable - meaning that it can't be a built in function.
Perhaps you mean something like this?
function getFn(fnName){
for (var l in yourObj){
if (l === fnName && yourObj[l] instanceof Function){
return [ l, yourObj[l] ];
}
}
return [fnName ,'not found'];
}
the loop iterates through the object and delivers an array containing the method name and a pointer to the method (or an error message).