主题:关于JavaScript函数的超级问题?
发表时间: 2008-07-09 10:09
问题在代码注释中,谁能解惑呢?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>函数测试</title>
</head>
<body>
<script>
var f = function fact(x){
if(x<=1) return 1 ;
else return x * fact(x-1);
};
alert(f(3));
alert(fact(3));//在火狐下该语句不能运行,报错:fact is not defined 这是为什么呢?
</script>
</body>
</html>
本来就没有定义的吗? fact都不存在。在 alert(fact(3)); 的时候, 环境中只存在f函数
你在仔细看看代码啊!function fact(x){
已经定义过了
var f = function fact(x){
if(x<=1) return 1 ;
else return x * fact(x-1);
};
你可以看看。 上面的内容是在函数内部定义的,而是直接赋值给 f 变量。
如果这样写你试试:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>函数测试</title>
</head>
<body>
<script>
function fact(x){
if(x<=1) return 1 ;
else return x * fact(x-1);
};
var f = fact;
alert(f(3));
alert(fact(3));//在火狐下该语句不能运行,报错:fact is not defined 这是为什么呢?
</script>
</body>
</html>
其它版块: