js閉包的運用 作用域

2021-10-04 12:27:17 字數 1035 閱讀 7344

function test(param)

}setinterval(test(1), 1000);//讓原本不能傳參的函式成為可以傳參

let counter = (function () 

return ,

decrement: function () ,

value: function ()

};})();

console.log(counter.value())

counter.increment()//對變數的操作只能通過閉包

console.log(counter.value())

counter = null//閉包生命結束

console.log(counter.value())

let num = 20

function test()

}let a = test()

console.log(a())//11

console.log(a())//12 閉包訪問的一直是區域性變數

let b = test()

console.log(b())//11 閉包有各自的變數,私有變數,各不衝突

for (var i = 0; i < 3; i++) 

console.log(i)//3 變數提公升

function test()

console.log(i)//i is not defined 用let定義的變數不被提公升

}test()

function test() 

console.log(i)

}test()

function test() 

console.log(i)

}test()

console.log(i)//i is not defined 變數只是被提公升到上一層作用域

js 作用域和閉包

作用域應用的特色情況,有兩種表現 自由變數的查詢,在函式定義的地方,向上級作用域查詢不是在執行的地方 函式作為返回值 function create const fn create const a 200 fn 100 函式作為引數 function print fn const a 100 fun...

JS作用域與閉包

vo ao 的解釋 1.作用域 es5中只有全域性作用域和函式作用域,我們都知道他沒有塊級作用域。es6中多了乙個let,他可以保證外層塊不受內層塊的影響。即內層塊形成了乙個塊級作用域,這是let的乙個特點。var a 1 function f1 f2 f1 2,1,2 上面的 有三個執行上下文環境...

js的作用域和閉包

1.作用域 乙個變數的可用範圍 全域性作用域 除了函式內,客廳 區域性作用域 函式內 小房間 全域性變數 在全域性作用域內宣告的變數 客廳裡面的東西 區域性變數 在區域性作用域內宣告的變數 你臥室裡面的東西 全域性作用域不能訪問區域性,區域性作用域可以訪問全域性 2.閉包 用來解決全域性汙染的,用來...