-3
function say667() {
    console.log(1);
    // Local variable that ends up within closure
    var num = 666;
    var sayAlert = function() {
            console.log(num);
        }
    num++;
    return sayAlert;
}
say667();

为什么这不起作用?它 consolelogs1但不 console.log num

4

4 回答 4

4

您正在返回实际函数,而不是调用函数,您需要在“sayAlert”之后添加 ()

function say667() {
    console.log(1);
    // Local variable that ends up within closure
    var num = 666;
    var sayAlert = function() {
            console.log(num);
        }
    num++;
    return sayAlert();
}
say667();

小提琴

于 2013-10-11T12:33:24.400 回答
3

而不是return sayAlert;你必须打电话return sayAlert();

(function() {
   console.log(1);
   // Local variable that ends up within closure
   var num = 666;
   var sayAlert = function() { console.log(num); }
   num++;
   return sayAlert();
})();

这里这个函数会自动调用。

或者和你的,

function say667() {
    console.log(1);
    // Local variable that ends up within closure
    var num = 666;
    var sayAlert = function() {
            console.log(num);
    }
    num++;
    return sayAlert();
}
say667();
于 2013-10-11T12:34:32.790 回答
1

为什么这不起作用?

因为say667()确实返回sayAlert函数(闭包),所以它不会调用它。尝试

var say = say667(); // logs 1 and returns the function
say(); // logs 667
say(); // logs 667 again
于 2013-10-11T12:46:17.097 回答
1

你可以打电话say667()();,但从垃圾收集器的角度来看,这并不是很好。最好return sayAlert()使用 say667 函数。

于 2013-10-11T12:37:34.403 回答