var factorial = function (num) { if (num <= 1) { return 1; } else { return num * factorial(num - 1); } }; console.log(factorial(5)); // 120; var anothorFactorial = factorial; factorial = null; console.log(anothorFactorial(5)); // Uncaught TypeError: factorial is not a function
在非严格模式下我们可以使用 num * arguments.callee(num - 1)来代替函数名。 严格模式下,通常会采用内联命名函数来解决这个问题。
function f(num) { if (num <= 1) { return 1; } else { return num*f(num - 1); } }; var factorial = f; var anothorFactorial = factorial; factorial = null; console.log(anothorFactorial(5)); // 120 f = null; console.log(anothorFactorial(5)); // Uncaught TypeError: f is not a function
给函数表达式的匿名函数命名并不会改变表达式的性质,即不会让它变成一个函数声明
1 2 3 4 5 6 7
var factorial = function f() { console.log(factorial == f); // true }
factorial(); //true console.log(typeof f); // undefined f(); // Uncaught ReferenceError: f is not defined