作用域鏈
- 函數(shù)在執(zhí)行的過程中补胚,先從自己內(nèi)部找變量
- 如果找不到,再?gòu)膭?chuàng)建當(dāng)前函數(shù)所在的作用域(詞法作用域)去找罩润,以此往上
- 注意找的是變量的當(dāng)前的狀態(tài)
函數(shù)聯(lián)通它的作用域鏈上的找的這個(gè)變量荠察,共同構(gòu)成閉包
一般情況下使用閉包主要是為了
- 封裝數(shù)據(jù)
- 暫存數(shù)據(jù)
典型閉包
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
封裝一個(gè)car對(duì)象
var Car = (function(){
var speed = 0;
//補(bǔ)充
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
如下代碼輸出多少?如何連續(xù)輸出 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
補(bǔ)全代碼,實(shí)現(xiàn)數(shù)組按姓名债蓝、年紀(jì)、任意字段排序盛龄。
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'))
寫一個(gè) sum 函數(shù)饰迹,實(shí)現(xiàn)如下調(diào)用方式。
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
待補(bǔ)充