<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>闭包循环问题</title>
<style type="text/css">
p {background:#ccc; width: 300px; height: 100px;}
</style>
</head>
<body>
<p id="p0">段落0</p>
<p id="p1">段落1</p>
<p id="p2">段落2</p>
<p id="p3">段落3</p>
<p id="p4">段落4</p>
<script type="text/javascript">
for( var i=0; i<5; i++ ) {
document.getElementById("p"+i).onclick=function() {
alert(i); //访问了父函数的变量i, 闭包
};
};
</script>
</body>
</html>
var pAry = document.getElementsByTagName("p");
for( var i=0; i< 5; i++ ) {
pAry[i].no = i;
pAry[i].onclick = function() {
alert(this.no);
}
};
var pAry = document.getElementsByTagName("p");
for( var i=0; i< 5; i++ ) {
pAry[i].no = i;
pAry[i].onclick = function() {
alert(this.no);
}
};
(function test() {
var temp =10;
for(var i=0; i< 5; i++ ){
document.getElementById("p"+i).onclick=function() {
alert(temp); //访问了父函数的变量temp, 闭包
}
};
temp=20;
})();
(function test() {
var temp =10;
for( var i=0; i< 5; i++ ) {
document.getElementById("p"+i).onclick=function() {
alert(temp); //访问了父函数的变量i, 闭包
}
if(i===1){
alert(temp);
}
};
temp=20;
})();
// js闭包this对象1
var name = 'The Window';
var object = {
name : 'My Object',
getNameFunc1 : function(){
// return this.name;
console.log(this);//object
return function(){//闭包,访问的便是全局变量的了,this指windows
console.log(this);//windows
return this.name; //The Window
}
},
getNameFunc2 : function(){
return this.name;//访问的是object
},
aa:function(){
alert(22);
}
};
alert(object.getNameFunc1()());//弹出“The Window”
// js闭包this对象2
var name = 'The Window';
var object = {
name : 'My Object',
getNameFunc : function(){
var that = this;
console.log(this);//输出的是object
return function(){
console.log(this);//输出的仍然是Windows
return that.name;
};
}
};
alert(object.getNameFunc()());//弹出“My Object”
function A(){
var a=1;
function B(){
return a;
};
return B;
};
var C=A();//C取得A的子作用域B的访问接口
console.log(C());//1 C能访问到B的父级作用域中的变量a
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有