案例11-閉包-傳參-幾種簡寫方式-重要!


另一種寫法:

<!DOCTYPE?html>

<html?lang="en">

<head>

????<meta?charset="UTF-8">

????<meta?name="viewport"?content="width=device-width,?initial-scale=1.0">

????<meta?http-equiv="X-UA-Compatible"?content="ie=edge">

????<title>Document</title>

</head>

<body>

<button>按鈕1</button>

<button>按鈕2</button>

<button>按鈕3</button>???

<script>

????匿名函數(shù)自執(zhí)行


????簡寫1:(函數(shù))();


(function(b){

????var?btns?=?document.querySelectorAll("button");

????console.log(b);

})(10);

/*

????全局污染:?不要使用全局變量,寫在fn自執(zhí)行里,也叫聲明一個命名空間

????var?tab?=?.....;

????var?tab?=?.....;??????覆蓋之前聲明

*/

(function(){?//?聲明一個命名空間

????var?btns?=?document.querySelectorAll("button");



????//?for(var?i?=?0;?i?<?btns.length;?i++){

????//?????btns[i].index?=?i;

????//?????btns[i].onclick?=?function(){

????//?????????console.log(this.index);

????//?????};

????//?}




????function?fn(index){

????????btns[index].onclick?=?function(){

????????????console.log(index);

????????};

????}

????for(var?i?=?0;?i?<?btns.length;?i++){

????????fn(i);

????}

????//?fn(0);

????//?fn(1);

????//?fn(2);

????//?fn(...100+);

})();???

</script>????

</body>

</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容