<script>
// 闭包 计算打车价格
//打车起步价13(3公里内),之后每多一公里增加5块钱,用户输入公里数就可以计算打车价格
//如果有拥堵情况,总价格多收取10块钱的拥堵费
var car = (function(){
var start = 13; //起步价
var total = 0; //总价
return{
price:function(n){
if(n <= 3){
total = start;
}else{
total = start + (n-3) *5
}
return total;
}, //正常价格
traffic:function(flag){
return flag ? total + 10 : total;
} //拥堵价格
}
})();
console.log(car.traffic(false));
console.log(car.price(5)); //23
console.log(car.traffic(true)); //33
console.log(car.price(1)); //13
console.log(car.traffic(false)); //13
二: 两个思考题 和解析
var name = 'The window';
var obj = {
name : 'myobject',
getNameFun:function(){
return function(){
return this.name;
}
}
}
console.log(obj.getNameFun()()); //The window
// 等价于
// var f = obj.getNameFun()
// var f = function(){
// return this.name
// }
// f() = function(){return this.name}() //解析为了立即执行函数,this指向window 所以返回了 The window 无闭包
var name = 'The window';
var obj = {
name : 'myobject',
getNameFun:function(){
var that = this;
return function(){
return that.name;
}
}
}
console.log(obj.getNameFun()()); //打印myobject 有闭包
//分析: var f = obj.getNameFun()
// var that = this;
//var f = function(){
// return that.name;
//}
</script>