var width = 10;
var height = 5;
drawBox(width,heigh);
希望する結果:
'drawBox(10,5);' <-- a string, not the returned value
機能しますが'drawBox(' + width + ',' + height + ');'
、これはあまりにも醜いです。さらに、多くの入力がありますが、2 つではありません。
この問題専用のスマート機能はありますか?
var width = 10;
var height = 5;
drawBox(width,heigh);
希望する結果:
'drawBox(10,5);' <-- a string, not the returned value
機能しますが'drawBox(' + width + ',' + height + ');'
、これはあまりにも醜いです。さらに、多くの入力がありますが、2 つではありません。
この問題専用のスマート機能はありますか?
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)
単なる好奇心から:
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)"
このようなもの ( http://jsfiddle.net/L2JJc/1/ )?
var createStrFunction = function(name, paramArray){
return name + "(" + paramArray.join(",") + ");";
}
createStrFunction("drawBox", [5,10]);