[英]Javascript - eval object creation?
我對 JavaScript 還是很陌生(雖然不是編碼),所以請隨意為我挑剔和白痴映射。
我試圖創建一些可以接受用戶輸入的東西。 如果第一個字符是感嘆號,它將嘗試使用該名稱創建一個對象並運行該對象的“action”方法。 否則它會將其視為常規文本(現在是警報)
<script type="text/javascript">
function GetInput(input){
// Trim the spaces off the beginning and end
input = input.trim();
if(input.charAt(0) != "!"){
// Just some normal text
alert(input);
return true;
}
/* Cut off the exclamation point, replace multiple spaces with one,
* and get the arguments if any. args[0] = the command. */
var args = input.substr(1).replace(/\s{2,}/g, " ").split(" ");
// Make sure the function is an object with a method named "action"
if(eval("typeof "+args[0]+";") === "function"
&& eval("typeof "+args[0]+".prototype.action;") === "function"){
eval("var command = new "+args[0]+"();");
command.action(args);
}else{
alert('"'+args[0]+'" is not a command.');
}
return true;
}
</script>
到目前為止,我注意到的唯一問題是 eval 語句。 我知道我可以使用 switch/case 和 eval 一起使用,甚至可以創建一個包含允許函數名稱的數組,並在 eval 之前將輸入與該數組進行比較,但我相信一定有更好的方法.
我只是希望能夠創建對象和方法而不更新任何內容(我認為這是鴨子類型的主要用途之一?)。 這可能沒有評估嗎? 如果沒有,是否有一種簡單的方法來清理字符串的輸入以避免諸如“! eval(alert('ub haxed'))
”或“! a;alert('ub haxed')
”之類的a;alert('ub haxed')
?
提前致謝
您應該只使用eval
一次來獲取函數,然后在變量中使用它執行所有操作。
var args = input.substr(1).split(/\s+/);
var fn = eval(args[0]);
if (typeof fn == 'function' && typeof fn.prototype.action == 'function') {
var command = new fn();
command.action(args);
} else {
alert('"'+args[0]+'" could not be evaluated to a valid command.');
}
return true;
如果這些構造函數是全局變量,您還可以將它們作為window
對象的屬性訪問:
var fn = window[ args[0] ];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.