问题在于,factorial显然应该是factorial()函数内部的局部变量的变量没有被声明为局部变量。修复只是使用var关键字声明它:
function factorial(b)
{
var factorial=1;
for(b; b > 1; b--)
{
factorial =b*factorial;
}
return factorial;
}
没有在函数factorial范围内声明为局部变量factorial(),factorial只引用factorial()函数对象,它具有全局范围,因为它是使用function factorial(){...}脚本顶层的语法声明的。
所以当里面的代码factorial()改变这个factorial引用指向一个数字值时,第二次factorial()调用将失败,因为全局变量factorial现在指向一个数字,而不是factorial()函数。
全局变量被广泛认为是javascript的坏处之一。这是一个很好的例子!
更新
For clarification, this issue is not confined to strictly global variables - it's just a general issue of function name scope. When a function is declared like function name(){...} that name has scope within the function and its parent. It's just that here, the parent context happens to be the global context.