Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a JavaScript function to return its own function call as a string?

In JavaScript, is it possible for a function to return its own function call as a string?

function getOwnFunctionCall(){
    //return the function call as a string, based on the parameters that are given to the function.
}

I want this function to simply return its own function call as a string (if it's even possible to do this):

var theString = getOwnFunctionCall(5, "3", /(a|b|c)/);
//This function call should simply return the string "getOwnFunctionCall(5, \"3\", "\/(a|b|c)\/")".
like image 606
Anderson Green Avatar asked Mar 23 '26 08:03

Anderson Green


1 Answers

I put this one up on jsFiddle: http://jsfiddle.net/pGXgh/.

function getOwnFunctionCall() {
    var result = "getOwnFunctionCall(";
    for (var i=0; i < arguments.length; i++) {
        var isString = (toString.call(arguments[i]) == '[object String]');
        var quote = (isString) ? "\"" : "";
        result += ((i > 0) ? ", " : "");
        result += (quote + arguments[i] + quote);
    }
    return result + ")";
}

alert(getOwnFunctionCall(5, "3", /(a|b|c)/));

Note that this should work for your example, but still needs work for arbitrarily complex objects/JSON included as a parameter.

like image 94
LouD Avatar answered Mar 25 '26 23:03

LouD