javascript中的“方法”过了一会就不等于自身了,怎么理解?
以前是玩c# winform的,感觉“函数”肯定总是不变的才对。。。但今天遇到个奇怪的问题,有没有高手从原理方面解释一下:为什么刚赋值时两个变量指向同一函数,过了一会就不指向同一函数了。。。原代码有点长,我已经尽量从实际环境中把没用的东西都去掉了。。。点两下checkbox,预期结果是两次提示true,结果第2次提示false
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<script>
var game = {action: null};
function setAction(b)
{
function doNothing()
{
}
if (b)
{
game.action = doNothing;
alert(game.action == doNothing)
}
else
{
alert(game.action == doNothing); //返回false,太奇怪了
game.action = null;
}
}
</script>
<label for="chk">show time</label><input id="chk" type="checkbox" onchange="setAction(this.checked)"/>
</body>
</html>
var game = {action: null};
function doNothing()
{
}
function setAction(b)
{
if (b)
{
game.action = doNothing;
alert(game.action == doNothing)
}
else
{
alert(game.action == doNothing); //返回false,太奇怪了
game.action = null;
}
}
var game = {action: null};
function setAction(b){
if(!setAction.doNothing){
setAction.doNothing = function(){
}
}
if (b){
game.action = setAction.doNothing;
alert(game.action == setAction.doNothing)
}else{
alert(game.action == setAction.doNothing); //返回false,太奇怪了
game.action = null;
}
}