- 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!
推薦閱讀
- Mastering Articulate Storyline
- Mastering OpenCV 4
- 用Flutter極速構建原生應用
- HTML5+CSS3網頁設計
- Express Web Application Development
- Swift Playgrounds少兒趣編程
- Android傳感器開發與智能設備案例實戰
- QlikView Unlocked
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- Java多線程并發體系實戰(微課視頻版)
- SQL Server實例教程(2008版)
- MySQL數據庫教程(視頻指導版)
- GO語言編程從入門到實踐
- Python程序設計現代方法
- 面向物聯網的Android應用開發與實踐