如何在JavaScript中从Function()中移除匿名性

3

我有一个从服务器端JavaScript返回的对象,它作为字符串发送,并尝试像这样恢复:

/* function that determines whether or not a String should be a function (namely, if it is the string form of a function)
 * Parameters: 
 *  • str : the string to check
 * Returns: 
 *  • true if str should be a function, or false otherwise
 * NOTE: the primary use for this function is for restoring stringified member functions of objects returned from the server
 */
function shouldBeFunction(str)
{
    str = str.toString().trim();
    // str should *not* be function iff it doesn't start with 'function'
    if (str.indexOf('function') !== 0) return false;
    // str should *not* be function iff it doesn't have a '(' and a ')'
    if ((str.indexOf('(') === -1) || (str.indexOf(')') === -1)) return false;
    // str should *not* be function iff it doesn't have a '{' and a '}'
    if ((str.indexOf('{') === -1) || (str.indexOf('}') === -1)) return false;
    return true;
}

/* reviver function for stringified objects that contain stringified methods 
 * Parameters : 
 *  • key   : the key of the object
 *  • value : the value of object[key]
 */
function objectReviver(key, value)
{ 
    var DEBUG = false;
    if ((typeof(value) === 'string') && (shouldBeFunction(value))) {
        if (DEBUG) {
            console.log('function string detected on property named : ' + key);
            console.log('function text: " ' + value + '"');
        }
        // get arguments list, if there is one to get
        var argsList = value.substring(value.indexOf('(') + 1, value.indexOf(')')).trim();
        if (DEBUG) console.log('argsList == ' + argsList);
        var functionBody = value.substring(value.indexOf('{') + 1, value.lastIndexOf('}')).trim();
        if (DEBUG) console.log('functionBody == ' + functionBody);
        if (argsList) 
            return new Function(argsList, functionBody);    
        return new Function(functionBody);
    }
    return value;
}

var myObj = JSON.parse(objStringFromServer, objectReviver);

然而,当我检查它的所有方法时,它们似乎都是匿名函数,在我的代码中会引起问题!(特别是,我有一个 Map<Object, String>,它似乎会深度比较 get() 中指定的 Object 与地图中的任何键,包括它的 toString() 方法。)我该如何解决这个问题?


有没有可能在同一行中声明和返回存在问题?请参见https://stackoverflow.com/questions/19145476/javascript-define-and-return-a-variable-on-one-line,其中涉及变量而非函数。 - Paul
1个回答

1

我在另一篇文章中找到了灵感: 有没有一种非eval的方法来创建一个以运行时确定名称的函数?

/* function that determines whether or not a String should be a function (namely, if it is the string form of a function)
 * Parameters: 
 *  • str : the string to check
 * Returns: 
 *  • true if str should be a function, or false otherwise
 * NOTE: the primary use for this function is for restoring stringified member functions of objects returned from the server
 */
function shouldBeFunction(str)
{
    str = str.toString().trim();
    // str should *not* be function iff it doesn't start with 'function'
    if (str.indexOf('function') !== 0) return false;
    // str should *not* be function iff it doesn't have a '(' and a ')'
    if ((str.indexOf('(') === -1) || (str.indexOf(')') === -1)) return false;
    // str should *not* be function iff it doesn't have a '{' and a '}'
    if ((str.indexOf('{') === -1) || (str.indexOf('}') === -1)) return false;
    return true;
}

/* reviver function for stringified objects that contain stringified methods 
 * Parameters : 
 *  • key   : the key of the object
 *  • value : the value of object[key]
 */
function objectReviver(key, value)
{ 
    var DEBUG = false;
    var argList = "";
    if ((typeof(value) === 'string') && (shouldBeFunction(value))) {
        if (DEBUG) {
            console.log('function string detected on property named : ' + key);
            console.log('function text: " ' + value + '"');
        }
        // get arguments list, if there is one to get
        var argsList = value.substring(value.indexOf('(') + 1, value.indexOf(')')).trim();
        if (DEBUG) console.log('argsList == ' + argsList);
        var functionBody = value.substring(value.indexOf('{') + 1, value.lastIndexOf('}')).trim();
        if (DEBUG) console.log('functionBody == ' + functionBody);
        var f = new Function(
            "return function " + key + "() {\n" +
            functionBody +
            "};"
        )();
        return f;
    }
    return value;
}

var myObj = JSON.parse('{"test":"function(){alert(1);}"}', objectReviver);
console.log(myObj.test);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接