var count = 0;
function goFast(){
++count;
console.log("Go straight and then ");
var direction = "right"; if (count%2===0){direction="left";}
turn(direction);
console.log("Thank you passenger #" + count);
}
var turn = function(direction) {
console.log("turn to your " + direction)
}
goFast();
goFast();
goFast功能负责计算有多少旅行者通过,并询问他们应该转向的另一个功能(可选择向左或向右注销)。
如何将我的count变量放在goFast函数中,从而更好地封装它,但是每次调用函数时都不重新初始化它?
这是一个jsfiddle:http://jsfiddle.net/legolandbridge/sU8T8/
答案 0 :(得分:4)
一种方法是将其包装在闭包中并返回一个可以访问count变量的函数。例如,
var goFast = (function() {
var count = 0;
return function() {
++count;
console.log("Go straight and then ");
var direction = "right"; if (count%2===0){direction="left";}
turn(direction);
console.log("Thank you passenger #" + count);
};
})();
答案 1 :(得分:3)
将其定义包含在另一个函数中以创建临时范围。
var goFast = (function() {
var count = 0;
return function() {
++count;
console.log("Go straight and then ");
var direction = "right"; if (count%2===0){direction="left";}
turn(direction);
console.log("Thank you passenger #" + count);
};
})();
答案 2 :(得分:0)
你可以做这样的事情,但它不是最漂亮的,因为turn
不在goFast()
之内..是的,没有看到好处。:
function goFast(){
if ( !window.count )
window.count = 0;
++count;
console.log("Go straight and then ");
var direction = "right"; if (count%2===0){direction="left";}
turn(direction);
console.log("Thank you passenger #" + count);
}
var turn = function(direction) {
console.log("turn to your " + direction)
}
goFast();
goFast();