我使用“Lazy Function Definition”模式来定义全局函数,如下所示:
if (bArmingSequenceComplete () ) {
console.log ("Good to go.");
}
// Code flows from high level to low level and support functions...
// vvvvv
function bArmingSequenceComplete () {
// In reality this is a long, complicated series of tests that only need to be done once.
var gtg = true;
if (gtg) {
bArmingSequenceComplete = function () { return true; };
}
else {
bArmingSequenceComplete = function () { return false; };
}
return bArmingSequenceComplete ();
}
这完美无瑕,整体代码很容易理解 我喜欢这种模式,因为它非常有效,并且很明显它正在做什么。
但JSHint给了我一些警告:
重新分配'bArmingSequenceComplete',这是一个函数。使用'var'或'let'来声明可能发生变化的绑定。
潜入some JSHint source code后,我发现这是由W021
选项控制的。所以我可以压制它:
// jshint -W021
if (gtg) {
bArmingSequenceComplete = function () { return true; };
}
else {
bArmingSequenceComplete = function () { return false; };
}
// jshint +W021
但是,JSHint告诉我一些有用的东西吗?定义这些函数真的是错误吗?
我是否可以全局停用所有此类警告而不会丢失一般的“重新分配”检查?
使用let
或var
建议 更糟糕的 代码(违反“最重要的顶级”规则和/或完全失败)。
例如:
if (bArmingSequenceComplete () ) {
console.log ("Good to go.");
}
// Code flows from high level to low level and support functions...
// vvvvv
let bArmingSequenceComplete = function () {
...
失败:
未捕获的ReferenceError:未定义bArmingSequenceComplete
和
if (bArmingSequenceComplete () ) {
console.log ("Good to go.");
}
// Code flows from high level to low level and support functions...
// vvvvv
var bArmingSequenceComplete = function () {
...
失败:
未捕获的TypeError:bArmingSequenceComplete不是函数
在使用前定义功能,违反了老板的“最重要或最高级别的顶级”规则。
答案 0 :(得分:-1)
恕我直言,使用IIFE
模式可以派上用场。 EG:
let bArmingSequenceComplete = (function () {
let gtg = true;
let outputMethod = null;
if (gtg) {
outputMethod = () => { return true; };
} else {
outputMethod = () => { return false; };
}
return outputMethod;
})();
if(bArmingSequenceComplete()) {
console.log('good to go');
}
<强>更新强>
由于您需要2个条件:
所以让我们这样试试吧:
function startHighLevelCode() {
if(bArmingSequenceComplete()) {
console.log('good to go');
}
}
let bArmingSequenceComplete = function () {
let gtg = true;
let outputMethod = null;
if (gtg) {
outputMethod = () => { return true; };
} else {
outputMethod = () => { return false; };
}
bArmingSequenceComplete = outputMethod;
return bArmingSequenceComplete();
};
// After all support functions
startHighLevelCode();