闭包,即函数连同它作用域链上的要找的这个变量,共同构成闭包。目的为暂存封装数据。如下为典型闭包案例:
function car(){
var speed = 0
function fn(){
speed++
console.log(speed)
}
return fn
}
var speedUp = car()
speedUp() //1
speedUp() //2
1.如下代码输出多少?如果想输出3,那如何改造代码?
var fnArr = [];
for (var i = 0; i < 10; i ++) {
fnArr[i] = function(){
return i
};
}
console.log( fnArr[3]() ) //输出10,返回函数但是未执行函数,for循环结束后输入fnArr[3],函数才执行,此时i等于10
思路:形成闭包,暂存数据
var fnArr[]
for(var i = 0, i<10, i++){
fnArr[i]=(function(j){
return function(){
return j
}
})(i)
}
console.log( fnArr[3]() )
2.封装一个car对象,满足如下功能
var Car = (function(){
var speed = 0;
//补充
return {
setSpeed: setSpeed,
getSpeed: getSpeed,
speedUp: speedUp,
speedDown: speedDown
}
})()
Car.setSpeed(30)
Car.getSpeed() //30
Car.speedUp()
Car.getSpeed() //31
Car.speedDown()
Car.getSpeed() //30
解答:
var Car = (function(){
var speed = 0;
function setSpeed(s){
speed=s
}
function getSpeed(){
return speed
}
function speedUp(){
speed++
}
function speedDown(){
speed--
}
//补充
return {
setSpeed: setSpeed,
getSpeed: getSpeed,
speedUp: speedUp,
speedDown: speedDown
}
})()
Car.setSpeed(30)
Car.getSpeed() //30
Car.speedUp()
Car.getSpeed() //31
Car.speedDown()
Car.getSpeed() //30
3.如下代码输出多少?如何连续输出 0,1,2,3,4?
for(var i=0; i<5; i++){
setTimeout(function(){
console.log('delayer:' + i )
}, 0)
}
解答:
delayer:5 //setTimeout为异步处理,for循环结束后才开始执行,即i=5
for(var i=0;i<5;i++){
satTimeout(function(j){
return function(){
console.log('delayer:'+ j)
}
})(i),0)
}
4.补全代码,实现数组按姓名、年纪、任意字段排序。
var users = [
{ name: "John", age: 20, company: "Baidu" },
{ name: "Pete", age: 18, company: "Alibaba" },
{ name: "Ann", age: 19, company: "Tecent" }
]
users.sort(byField('age'))
users.sort(byField('company'))
解答:
function byName(user1, user2){
return user1.name > user2.name
}
function byAge (user1, user2){
return user1.age > user2.age
}
或者:
function byFeild(field){
return function(user1, user2){
return user1[field] > user2[field]
}
}
users.sort(byField('company'))
5.写一个 sum 函数,实现如下调用方式。
console.log( sum(1)(2) ) // 3
console.log( sum(5)(-1) ) // 4
解答:
function cat(i){
return function(j){
return i+j
}
}
参考:http://book.jirengu.com/fe/%E5%89%8D%E7%AB%AF%E5%9F%BA%E7%A1%80/Javascript/%E9%97%AD%E5%8C%85.html