闭包,生命周期,回收机制
闭包:子函数使用父函数
子函数可以延迟父函数变量的生命周期,可以拓展父函数的空间
在js中内部的局部变量只允许其子函数使用
父函数没有办法使用子函数的局部变量
子函数可以使用父函数的局部变量
<script type="text/javascript">
function a(){
var c = 10;
function b(){
var f = 20;
console.log(c);
function d(){
console.log(c);
}
}
b();
console.log(f);
}
a();
</script>
生命周期:
·当js检测不到该变量使用,就会杀死该变量,如果想延长其变量的生命周期,那么就可以从新声明一个新变量,给予之前的变量的值
如果想让变量得到永恒
<script type="text/javascript">
function a(){
var c = 10;
function b(){
var f = 20;
console.log(c);
function d(){
console.log(c);
}
}
b();
console.log(f);
}
a();
</script>
回收机制
a = null 回收了
if(){
}
else if(){
}
<script type="text/javascript">
var a = 4;
if(a != 9){
alert(1);
}
else if(a == 10){
alert(2);
}
else if(a == 4){
alert(3);
}
else
{
alert(4);
}
</script>
!=
<script type="text/javascript">
function a(){
alert(1);
}
console.log(a);
</script>
这个可以返回函数自己的地址
<script type="text/javascript">
function a(){
alert(1);
}
setTimeout(a,1000);
</script>
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<button id = 'btn1'>1</button>
<script type="text/javascript">
var btn2 = document.getElementById('btn1');
btn2.onclick = function(){
alert(1);
};
</script>
</body>
</html>
这样可以实现点按键1,弹出警告
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<button id = 'btn1'>1</button>
<script type="text/javascript">
btn1.onclick = a;
function a(){alert(1)};
</script>
</body>
</html>
随机数
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<button id = 'btn1'>1</button>
<script type="text/javascript">
setInterval(function(){
console.log(Math.random())}
,500);
</script>
</body>
</html>