- 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!
推薦閱讀
- Designing Machine Learning Systems with Python
- Java Web及其框架技術(shù)
- Python進(jìn)階編程:編寫更高效、優(yōu)雅的Python代碼
- 營(yíng)銷數(shù)據(jù)科學(xué):用R和Python進(jìn)行預(yù)測(cè)分析的建模技術(shù)
- C語言程序設(shè)計(jì)立體化案例教程
- Hands-On JavaScript High Performance
- Visual FoxPro程序設(shè)計(jì)
- Oracle GoldenGate 12c Implementer's Guide
- JavaScript應(yīng)用開發(fā)實(shí)踐指南
- HTML+CSS+JavaScript網(wǎng)頁制作:從入門到精通(第4版)
- AMP:Building Accelerated Mobile Pages
- Learning Kotlin by building Android Applications
- Greenplum構(gòu)建實(shí)時(shí)數(shù)據(jù)倉庫實(shí)踐
- Spark技術(shù)內(nèi)幕:深入解析Spark內(nèi)核架構(gòu)設(shè)計(jì)與實(shí)現(xiàn)原理
- Android初級(jí)應(yīng)用開發(fā)