如何将函数调用转换为首先评估输入的字符串

How to convert function call to string with inputs evaluated first?

本文关键字:评估 输入 字符串 函数调用 转换      更新时间:2023-09-26
var width = 10;
var height = 5;
drawBox(width,heigh);

想要的结果:

'drawBox(10,5);'  <-- a string, not the returned value

虽然'drawBox(' + width + ',' + height + ');'有效,但这太丑陋了,而且我有很多输入,但没有两个。

有没有专门针对这个问题的智能功能?

您可以使用新属性扩充Function 的原型,如下所示:

Function.prototype.callAndGetSR = function() {
    this.call(this, arguments); 
    return this.name + '(' + Array.prototype.slice.call(arguments).join(', ') + ')';
}

SR 代表字符串表示)。
这样称呼它:

drawBox.callAndGetSR(5,10); 

此调用绘制框并返回带有所用参数的函数名称,即 drawBox(5, 10) .此新属性假定您不从 drawBox 函数返回任何内容。

如果您需要从函数返回drawBox并获取函数及其参数的字符串表示形式,则可以将其写入日志:

Function.prototype.callAndGetSR = function() {
    console.log(this.name + '(' + Array.prototype.slice.call(arguments).join(', ') + ')');
    this.call(this, arguments); 
}
drawBox.callAndGetSR(5,10); // writes drawBox(5, 10) to log first, after that invokes the drawBox function

或者,您可以简化新属性并使其返回字符串表示形式,而无需调用函数:

Function.prototype.getSR = function() {
    return this.name + '(' + Array.prototype.slice.call(arguments).join(', ') + ')';
}
drawBox.getSR(5,10); // returns drawBox(5, 10)

像这样的东西(http://jsfiddle.net/L2JJc/1/)?

var createStrFunction = function(name, paramArray){
    return name + "(" + paramArray.join(",") + ");";
}
createStrFunction("drawBox", [5,10]);

只是出于好奇:

function funcToString(func, params) {
    return func.name + "("
               + [].slice.call(arguments, 1).slice(0, func.length).join(",")
           + ")";
}

按如下方式调用它:

function foo(a, b) { /* ... */ };
var width = 10, height = 20;
funcToString(foo, width, height); // returns "foo(10,20)"