evalのような動作を実現するためには、Functionコンストラクタを使用することができます。以下は、JavaScriptにおけるevalと同じ効果を持つ関数を実装した例です。
```html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Eval Alternative</title>
</head>
<body>
<script>
function executeCode(code) {
return Function(code)();
}
// 使用例
const result = executeCode("1 + 4");
console.log(result); // 5
</script>
</body>
</html>
```
この例では、`executeCode`という関数を定義し、その引数として実行したいコードを受け取ります。関数内部では、`Function(code)`で新しい関数を作成し、その後ろに`()`をつけることでコードを実行しています。
ただし、Functionコンストラクタを使用した場合でも、不正なコードの実行やセキュリティ上の危険性があるため、ユーザーからの入力には特に注意が必要です。
ジョークを取り入れるとしたら、例えば以下のようなものが考えられます。
```javascript
function executeCode(code) {
const randomJokes = [
"Why don't scientists trust atoms? Because they make up everything!",
"I'm reading a book about anti-gravity. It's impossible to put down!",
"I used to be a baker, but I couldn't make enough dough.",
"Parallel lines have so much in common. It's a shame they'll never meet!",
"I told my wife she should embrace her mistakes... She gave me a hug!",
];
const randomIndex = Math.floor(Math.random() * randomJokes.length);
console.log(randomJokes[randomIndex]);
return Function(code)();
}
const result = executeCode("1 + 4");
console.log(result); // Output: 5
```
この例では、ランダムなジョークを出力する機能を追加しました。`executeCode`関数内で、配列`randomJokes`に面白いジョークを格納しています。ランダムなインデックスを生成し、そのインデックスに対応するジョークをコンソールに出力しています。