js閉包的與非閉包的對比
阿新 • • 發佈:2018-12-23
專案目錄結構
cosure.js的程式碼如下:
//閉包 function test(){ var arr = []; for (var i = 0; i < 10; i++) { //閉包的寫法就是 一個圓括號裡面包了一個匿名函 // 把需要儲存的值,通過引數傳遞 ( function(j) { arr[j] = function(){ document.write(j + " "); } }(i) ) } return arr; } var myArr = test(); for (var i = 0; i < 10; i++) { myArr[i](); }
閉包的程式碼
cosure.html程式碼如下:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="js/cosure.js"></script>
</head>
<body>
</body>
</html>
執行的效果如下:
---------------------------------分割線--------------------------------------
非閉包的程式碼
//非閉包的情況
function test(){
var arr = [];
for (var i = 0; i < 10; i++) {
arr[i] = function(){
document.write(i + " ");
}
}
return arr;
}
var myArr = test();
for (var i = 0; i < 10; i++) {
myArr[i]();
}
uncosure.html的程式碼如下:
執行如下:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="js/uncosure.js"></script> </head> <body> </body> </html>
閉包與非閉包,閉包實現迴圈給兩個按鈕繫結事件,並alert當選for迴圈的index值(相關程式碼array.js和array.html)
介面如下:1.閉包btn
array.js 如下:function bindBtn() {
var btnArr = new Array();
for (var i = 1; i <= 2; i++) {
btnArr[i] = document.getElementById("btn" + i);
(
function(obj,index){ //閉包函式繫結事件
obj.onclick = function(){
alert("百度經驗" + index );
}
}(btnArr[i],i)
)
}
// alert(btnArr);
console.log(btnArr, "obj");
console.log(btnArr.constructor, "constructor"); //ƒ Array() { [native code] }
console.log(btnArr.prototype, "prototype");
}
window.onload = function() {
unbindBtn();
//bindBtn();
}
array.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="btn1">btn1</button>
<button id="btn2">btn2</button>
<script src="js/array.js"></script>
</body>
</html>
點選 btn1
點選 btn2
2.非閉包btn
array.html如上。 array.js程式碼如下:function bindBtn() {
var btnArr = new Array();
for (var i = 1; i <= 2; i++) {
btnArr[i] = document.getElementById("btn" + i);
(
function(obj,index){ //閉包函式繫結事件
obj.onclick = function(){
alert("百度經驗" + index );
}
}(btnArr[i],i)
)
}
// alert(btnArr);
console.log(btnArr, "obj");
console.log(btnArr.constructor, "constructor"); //ƒ Array() { [native code] }
console.log(btnArr.prototype, "prototype");
}
window.onload = function() {
// unbindBtn();
bindBtn();
}
點選 btn1
點選 btn2