重构函数内的Javascript函数

时间:2017-08-22 04:11:07

标签: javascript html function dom refactoring

我想要一些关于重构以下代码的技巧,说实话,它并不复杂,但我仍然在学习最佳实践和约定。

HTML:

<div class="joke-container">
  <div class="joke-text">
    "This is a boring Static Joke"
  </div>
  <div class="joke-control">
    <button type="button" value="Random">Random</button>
  </div>
</div>

JS:

const jokes = [
  '"This is a very funny Joke"',
  '"This is another super crazy Joke"',
  '"OMFG this is so random"'
];

const randomJokeButton = document.querySelector(
  "button[type=button][value=Random]"
);

function randomJoke(jokes) {
  return (joke = jokes[Math.floor(Math.random() * jokes.length)]);
}

function printJoke(joke) {
  let jokeText = document.querySelector(".joke-text");
  return (jokeText.textContent = joke);
}

randomJokeButton.addEventListener("click", () => {
  printJoke(randomJoke(jokes));
});

SCSS:

@mixin center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.joke-container {
  @include center;
  background: white;
  padding: 40px;
  width: 900px;
}

.joke-text {
  margin-bottom: 20px;
}

body {
  background: papayawhip;
}

button {
  background: papayawhip;
  border: 0;
  padding: 8px;
  min-width: 100px;
}

所以我不太确定的部分是:

randomJokeButton.addEventListener("click", () => {
  printJoke(randomJoke(jokes));
});

基本上,我在带有参数的另一个函数中调用函数的方式并不能让我高兴,也许这是我不知道的正确方法,也许我应该将它放在变量中?。

我有一个codepen项目。

0 个答案:

没有答案