在函数内部调用函数表达式... JavaScript

时间:2014-04-18 18:03:46

标签: javascript function expression

我在理解函数表达式的原因(在另一个函数内)时只是在以下源代码中调用alert命令时遇到了问题。

请用初学者的语言向我解释。高级感谢每一位贡献者。

    var parkRides = [ ["Birch Bumpers", 40], ["Pines Plunge", 55], ["Cedar Coaster", 20], ["Ferris Wheel of First", 90] ];

    var fastPassQueue = ["Cedar Coaster", "Pines Plunge", "Birch Bumpers", "Pines Plunge"];

    function buildTicket (allRides, passRides, pick) 
    {
        if(passRides[0] == pick)
        {
            var pass = passRides.shift();
            // Why does the alert command have to be put inside a function expression?  Why do we even need a function expression? 
            return function() 
            {
                alert("Quick, you have a fast pass to " + pass);
            };
        }

        else
        {
            for (var i = 0; i < allRides.length; i++)
            {
                if(allRides[i][0] === pick)
                {
                    // Why is this function being declared again?   
                    return function () 
                    {
                        alert("A ticket is printing for " + pick + "!\n" + "Your wait time is about " + allRides[i][1] + " minutes.");    
                    };
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

函数buildTicket返回一个函数,当你调用它时它会提醒结果。你可以使用这样的东西:

// call the function
var f = buildTicket(x, y, z);

// display the result
f();