在定义闭包(或模块模式)时,我看到一些开发人员使用函数表达式,例如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
};
})();