0

可能重复:
在 JavaScript 中使用 var 和不使用 var 的区别

这两种方法的主要区别是什么。有人可以帮我理解。如果在函数中使用“var”关键字声明变量,这意味着什么?在这两种情况下,计时器都按预期在 3 秒内清除。

Approach 1:
<html>
<body>
<script type="text/javascript">
function function2()
{
int=self.setInterval(function(){
alert(int);
clearInterval(alert("in clear"+ int));
},3000);
}
</script>
<button onclick="function2()">Start</button>
</body>
</html>

Approach 2


<html>
<body>
<script type="text/javascript">
function function2()
{
var int=self.setInterval(function(){
alert(int);
clearInterval(alert("in clear"+ int));
},3000);
}
</script>
<button onclick="function2()">Start</button>
</body>
</html>
4

1 回答 1

2

如果不使用 var,您会将该变量隐式放入全局命名空间中。使用 var 变量是函数的局部变量。

于 2012-04-26T01:22:11.667 回答