0

When defining a closure (or module pattern) I've seen some developers use either a function expression e.g. var f = function{...}; or use a function declaration function f {...}.

I understand hoisting and the general differences, but I'm concerned about any differences that might apply in a closure.

I'm wondering which is preferred and why? Any advantages/disadvantages? If there are no general differences which is more common?

Consider the two styles below:

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
    };

})();
4

0 回答 0