本文內(nèi)容學(xué)習(xí)于:后盾人 (houdunren.com)
1.作用域
1)函數(shù)被執(zhí)行后其環(huán)境變量將從內(nèi)存中刪除。下面函數(shù)在每次執(zhí)行后將刪除函數(shù)內(nèi)部的 total 變量。
?function count() {
????????let total = 0;
}
count ();
2)函數(shù)每次調(diào)用都會創(chuàng)建一個新作用域
3)如果子函數(shù)被使用時父級環(huán)境將被保留(構(gòu)造函數(shù)也是很好的環(huán)境例子)
function hd() {
let n = 1;
return function() {
let b = 1;
return function() {
????????console.log(++n); console.log(++b);
};文章來源:http://www.zghlxwxcb.cn/news/detail-620040.html
};
}
let a = hd() () ;
a(); //2,2
a(); //3,3
4)let/const,使用let/const 可以將變量聲明在塊作用域中(放在新的環(huán)境中,而不是全局中)
5)在 for 循環(huán)中使用let/const 會在每一次迭代中重新生成不同的變量
let arr = [];
for (let i = o; i < 10; i++) {
arr.push((() => i)
};
console.log(arr[3]());//3 如果使用var聲明將是10
6)在沒有l(wèi)et/const 的歷史中使用以下方式產(chǎn)生作用域
//1.自行構(gòu)建閉包 var arr = [];
for (var i = o; i < 10; i++) {
(function (a){
arr.push(()=>a);
}) (i);
}
console.log(arr[3]()); //3
//2.閉包
閉包指:子函數(shù)可以訪問外部作用域變量的函數(shù)特性,即使在子函數(shù)作用域外也可以訪問。
·Js中的所有函數(shù)都是閉包
閉包一般在子函數(shù)本身作用域以外執(zhí)行,即延伸作用域
1)閉包基本展示
function hd() {
let name ='后盾人;
return function () {
return name;
}
let hdcms = hd();
console.log(hdcms());//后盾人
2)使用閉包返回數(shù)組區(qū)間元素
let arr = [3, 2, 4,1, 5,6];
function between(a, b) {
return function(v) {
return v >= a && v <= b;
};
}
console.log(arr.filter(between(3,5)));
*3)閉包排序,使用閉包按指定字段排序
let lessons = [
{title:"媒體查詢響應(yīng)式布局", click:89, price:12},
{title:"FLEX 彈性盒模型" click:45, price: 120},
{title:"GRID 柵格系統(tǒng)", click:19, price:67},
{title:"盒子模型詳解" click: 29, price: 300}
];
function order(field){
return (a, b) => (a[field] > b[field] ? 1 :-1);
}
console.table(lessons.sort(order("price")));
*4)閉包問題
(1)內(nèi)存泄漏
閉包特性中,上級作用域會為函數(shù)保存數(shù)據(jù),從而造成的如下所示的內(nèi)存泄漏問題
<body>
<div desc="houdunren">在線學(xué)習(xí)</div><div desc="hdcms">開源產(chǎn)品</div>
</body>
<script>
let divs = document.querySelectorAll ("div");
divs.forEach(function(item) {
item.addEventListener("click",function() {
console.log(item.getAttribute("desc"));
});
item && console.log(item.getAttribute("desc"));// 回調(diào)函數(shù)外面,依然可以訪問});
</script>
***下面通過清除不需要的數(shù)據(jù)解決內(nèi)存泄漏問題
let divs = document.querySelectorAll ("div");
divs.forEach(function(item) {
let desc = item.getAttribute("desc");
item.addEventListener("click",function() {
console.log(desc);
})
item =null;
item && console.log(item.qetAttribute("desc"));// 回調(diào)函數(shù)外面,清除了不需要的數(shù)據(jù),就不可訪問了
});
(2)this 指向
this 總是指向調(diào)用該函數(shù)的對象,即函數(shù)在搜索 this 時只會搜索到當前活動對象。
下面是函數(shù)因為是在全局環(huán)境下調(diào)用的,所以 this 指向 window,這不是我們想要的。
let hd = {
user:"后盾人",
get:function(){
return function() {
return this.user;};
}
};
console.log(hd.get()());//undefined
***使用箭頭函數(shù)解決這個問題
let hd = {
user:"后盾人",
get:function(){
return () => this.user;
}
};
console.log(hd.get()());//后盾人文章來源地址http://www.zghlxwxcb.cn/news/detail-620040.html
到了這里,關(guān)于JavaScript 作用域與閉包的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!