JavaScript:函数闭包演示

测试网址:
http://www.w3cschool.cn/tryrun/showhtml/tryjs_lightbulb

源代码:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>JavaScript闭包演示</title> 
</head>
<body>
     
<script>
var changeImage = (function changeImage()
{   
	var album = [
        "/statics/images/course/pic_bulboff.gif",
        "/statics/images/course/pic_bulbon.gif"
    ];
 
    var selectIndex = 0;
     
    return function(obj){
        selectIndex = (++selectIndex) % 2;
        obj.src = album[selectIndex];
    };
})();
</script>
 
<img onclick="changeImage(this)" src="/statics/images/course/pic_bulboff.gif" width="100" height="180" />
<p>点击灯泡就可以打开或关闭这盏灯</p>  
</body>
</html>

Comments are closed.