官术网_书友最值得收藏!

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!

主站蜘蛛池模板: 莆田市| 葫芦岛市| 开化县| 兴义市| 凭祥市| 分宜县| 镶黄旗| 景东| 金平| 京山县| 隆化县| 清水县| 兴义市| 凉城县| 蓝山县| 汽车| 合江县| 萝北县| 武鸣县| 通渭县| 四平市| 广水市| 长岭县| 衡阳县| 静乐县| 龙州县| 高陵县| 涿州市| 长岛县| 通化市| 泰来县| 青冈县| 昌邑市| 苏州市| 灌阳县| 巫溪县| 类乌齐县| 瓦房店市| 和龙市| 高邮市| 喀喇沁旗|