如何将函数调用转换为首先评估输入的字符串
How to convert function call to string with inputs evaluated first?
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)"
例
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 可以't让我的if语句处理js中的html表单输入
- 名称输入的索引
- 如何编写HTML输入的JS内联
- 要求输入在数据列表中
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 让文本输入幻灯片显示输入时的新文本输入?然后向后滑动
- 如何将输入(type=text)从html表单传递到javascript函数
- 单击jquery清除输入值
- 而循环只设置php中输入字段中的第一个值
- 在输入字段中将最小金额设置为
- jQuery自定义验证比较多个输入的序列
- 在使用onblur进行输入评估时,是否可以获得单击对象的元素id
- 如何将函数调用转换为首先评估输入的字符串
- 具有所需 JavaScript 文件的 Jupyter 输入单元在页面加载时进行评估
- 在 Java 中将用户输入作为 JavaScript 进行评估时的安全风险
- JavaScript 比较运算符未正确评估用户输入
- 使用javascript评估表单输入单选按钮
- 如何评估用户在web应用程序中输入的代码
- 安全地解析和评估用户输入