- Mastering JavaScript Functional Programming
- Federico Kereki
- 209字
- 2021-07-02 22:41:10
Solution #2 - use a global flag
The solution most people would probably think of first, is using some global variable to record whether the user has already clicked on the button. You'd define a flag named something like clicked, initialized with false. When the user clicks on the button, if clicked was false, you change it to true, and execute the function; otherwise, you don't do anything at all:
let clicked = false;
.
.
.
function billTheUser(some, sales, data) {
if (!clicked) {
clicked = true;
window.alert("Billing the user...");
// actually bill the user
}
}
For more good reasons NOT to use global variables,
read http://wiki.c2.com/?GlobalVariablesAreBad.
This obviously works, but it has several problems that must be addressed:
- You are using a global variable, and you could change its value by accident. Global variables aren't a good idea, neither in JS nor in other languages.
- You must also remember to re-initialize it to false when the user starts buying again. If you don't, the user won't be able to do a second buy, because paying will have become impossible.
- You will have difficulties testing this code, because it depends on external things (that is, the clicked variable).
So, this isn't a very good solution... let's keep thinking!
推薦閱讀
- Instant Testing with CasperJS
- 深入理解Bootstrap
- 數據庫程序員面試筆試真題與解析
- Testing with JUnit
- 編程卓越之道(卷3):軟件工程化
- 區塊鏈架構與實現:Cosmos詳解
- 現代C++編程實戰:132個核心技巧示例(原書第2版)
- ScratchJr趣味編程動手玩:讓孩子用編程講故事
- 運維前線:一線運維專家的運維方法、技巧與實踐
- 大學計算機應用基礎(Windows 7+Office 2010)(IC3)
- Node.js應用開發
- Learning Dynamics NAV Patterns
- 基于Docker的Redis入門與實戰
- Scratch編程入門與算法進階(第2版)
- Web前端開發全程實戰:HTML5+CSS3+JavaScript+jQuery+Bootstrap