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

Solution #7- use a local flag

We can go back to the idea of using a flag, but instead of making it global (which was our main objection) we can use a Immediately Invoked Function Expression (IIFE): we'll see more on this in Chapter 3, Starting Out with Functions - A Core Concept, and in Chapter 11, Implementing Design Patterns - The Functional Way. With this, we can use a closure, so clicked will be local to the function, and not visible anywhere else:

var billTheUser = (clicked => {
return (some, sales, data) => {
if (!clicked) {
clicked = true;
window.alert("Billing the user...");
// actually bill the user
}
};
})(false);

See how clicked gets its initial false value, from the call at the end.

This solution is along the lines of the global variable solution, but using a private, local variable is an enhancement. About the only objection we could find, is that you'll have to rework every function that needs to be called only once, to work in this fashion. (And, as we'll see in the following section, our FP solution is similar in some ways to it.) OK, it's not too hard to do, but don't forget the Don't Repeat Yourself (D.R.Y) advice!

主站蜘蛛池模板: 论坛| 无棣县| 桐柏县| 周至县| 白朗县| 禄丰县| 方城县| 通化县| 光泽县| 涟水县| 香港| 津市市| 汝城县| 额敏县| 丹江口市| 吉安县| 屯门区| 紫金县| 沂水县| 布尔津县| 易门县| 巴彦县| 亳州市| 永胜县| 巍山| 临沂市| 德江县| 青浦区| 桃源县| 连州市| 湘潭县| 和静县| 大名县| 九龙县| 东乡族自治县| 双城市| 封丘县| 广丰县| 西城区| 大港区| 乐至县|