在javascript中定义闭包时,最好将方法定义为函数表达式或声明(以及为什么)?

时间:2013-05-29 04:31:41

标签: javascript function closures

在定义闭包(或模块模式)时,我看到一些开发人员使用函数表达式,例如var f = function{...};或使用函数声明function f {...}

我理解悬挂和一般差异,但我担心在闭包中可能存在的任何差异。

我想知道哪个更受欢迎,为什么?有什么优点/缺点?如果没有比较常见的一般差异吗?

考虑以下两种风格:

var deepThought = (function(){

    var someSecret = "42";

    function whatIsTheAnswerToTheUltimateQuestion() {
        return someSecret;
    }

    function whatIsTheUltimateQuestion() {
        return "I'm not sure yet. You might have to wait a while...";
    }

    return {
        whatIsTheAnswerToTheUltimateQuestion : whatIsTheAnswerToTheUltimateQuestion,
        whatIsTheUltimateQuestion : whatIsTheUltimateQuestion
    };

})();

var deepThought2 = (function(){

    var someSecret = "41";

    var whatIsTheAnswerToTheUltimateQuestion = function () {
        return someSecret;
    };

    var whatIsTheUltimateQuestion = function () {
        return "I'm not sure yet. You might have to wait a while...";
    };

    return {
        whatIsTheAnswerToTheUltimateQuestion : whatIsTheAnswerToTheUltimateQuestion,
        whatIsTheUltimateQuestion : whatIsTheUltimateQuestion
    };

})();

0 个答案:

没有答案