作用域链
- 函数在执行的过程中,先从自己内部找变量
- 如果找不到,再从创建当前函数所在的作用域(词法作用域)去找,以此往上
- 注意找的是变量的当前的状态
函数联通它的作用域链上的找的这个变量,共同构成闭包
一般情况下使用闭包主要是为了
- 封装数据
- 暂存数据
典型闭包
function car(){
var speed = 0
function fn(){
speed++
console.log(speed)
}
return fn
}
var speedUp = car()
speedUp() //1
speedUp() //2
如下代码输入出多少?如果输出3,那如何改造代码?
var fnArr = [];
for (var i = 0; i < 10; i ++) {
fnArr[i] = function(){
return i
};
}
console.log( fnArr[3]() )
var fnArr = [];
for (var i = 0; i < 10; i++) {
(function (i) {
fnArr[i]= function () {
return i
}
})(i);
}
console.log( fnArr[3]() )//3
封装一个car对象
var Car = (function(){
var speed = 0;
//补充
return {
setSpeed: setSpeed,
get: get,
speedUp: speedUp,
speedDown: speedDown
}
})()
Car.set(30)
Car.get() //30
Car.speedUp()
Car.get() //31
Car.speedDown()
Car.get() //30
var Car = (function(){
var speed = 0;
function set(speed1){
speed = speed1
console.log(speed)
}
function get(){
console.log(speed)
return speed;
}
function speedUp(){
speed++;
console.log(speed)
}
function speedDown(){
speed--;
console.log(speed)
}
return {
set: set,
get: get,
speedUp: speedUp,
speedDown: speedDown
}
})()
Car.set(30)
Car.get() //30
Car.speedUp()
Car.get() //31
Car.speedDown()
Car.get() //30
如下代码输出多少?如何连续输出 0,1,2,3,4?
for(var i=0; i<5; i++){
setTimeout(function(){
console.log('delayer:' + i )
}, 0)
}
(function (j) {
setTimeout(() => {
console.log( + j )
}, 0);
})(i)
}
//0,1,2,3,4
如下代码输出多少?
function makeCounter() {
var count = 0
return function() {
return count++
};
}
var counter = makeCounter()
var counter2 = makeCounter();
console.log( counter() ) // 0
console.log( counter() ) // 1
console.log( counter2() ) // ?
console.log( counter2() ) // ?
function makeCounter() {
var count = 0
return function() {
return count++
};
}
var counter = makeCounter()
var counter2 = makeCounter();
console.log( counter() ) // 0
console.log( counter() ) // 1
console.log( counter2() ) // 0
console.log( counter2() ) // 1
补全代码,实现数组按姓名、年纪、任意字段排序。
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'))
var users = [
{ name: "John", age: 20, company: "Baidu" },
{ name: "Pete", age: 18, company: "Alibaba" },
{ name: "Ann", age: 19, company: "Tecent" }
]
function byField(string){
return function(user1,user2){
return user1[string] >user2[string]
}
}
users.sort(byField('age'));
users.sort(byField('name'))
users.sort(byField('company'))
写一个 sum 函数,实现如下调用方式。
console.log( sum(1)(2) ) // 3
console.log( sum(5)(-1) ) // 4
function sum(a) {
return function (b) {
return a + b;
}
}
console.log( sum(1)(2) ) // 3
console.log( sum(5)(-1) ) // 4
待补充