使用 javascript 自调用匿名函数

the use of javascript self invoke anonymous function

请看下面的代码块。哪一个是最好的选择?基本上他们都在做同样的事情

示例 1

var otherVars1
var otherVars2
var otherVars3
var valid; // create a boolean variable
// some precondition to set valid to true or false
.... 

if (valid || someRegex.test(value)) {
  ...
}

示例 2

var otherVars1
var otherVars2
var otherVars3

// create a function that return a boolean
function isValid() {
  ...
  return Boolean
}

if (isValid() || someRegex.test(value)) {
 ...
}

示例 3

var otherVars1
var otherVars2
var otherVars3

// use self-invoke anonymous function directly
if ((function() {
...
return Boolean })() || someRgex.test(value)) {
  ...
}

比较这三个例子,我更喜欢使用自调用匿名函数(例子3),原因如下

如果我在以上任何一点上有错误,请纠正我,并告诉我您的偏好和原因是什么?

我会说你可以使用 immediate invocation of function expressions 但你可以避免在 if 中使用它们,你可以如下使用。

这将避免不必要的global scope变量声明、函数等

(function() {
  var otherVars1
  var otherVars2
  var otherVars3
  var valid; // create a boolean variable
  // some precondition to set valid to true or false
  .... 

  if (valid || someRegex.test(value)) {
    ...
  }

})();