是 JavaScript 中的一个函数

Is IF a function in JavaScript?

本文关键字:一个 函数 JavaScript      更新时间:2023-09-26

我一直在探索JavaScript中的范围。消息来源指出,范围是函数分隔的,而不是像大多数语言那样以块分隔的。

我在我正在编写的一些代码中放置了一些显示代码,因为我的一些函数中的函数不清楚(对我来说),我想看看这些范围是如何工作的。

最大的惊喜是,在 $.getJSON 函数中的 $.each 函数中,if(){} 子句显然被视为一个函数。我本来以为它是一个块。

function displayInfo(nKey) {
    if(!nKey) var nKey = 0;
    var objFilm = {};
    var imgRef;
    //iterate through all object properties; display their attributes
    // Object.keys() returns an array of all property names
    // for most entries, the object is ...film; check first for array of multiple films
    jqxhr = $.getJSON('dbMovies.json', function(data) {
        var xx = "xx";
        $.each(data.disc, function(i, xdata) {
            if(xdata.key == nKey) {
                objFilm = xdata.film;
                var yy = "yy";
                imgRef = xdata.img;
                return false;
            }
console.log("in jqxhr, xx: " + typeof xx);  //this shows
console.log("in jqxhr, yy: " + typeof yy);  //this does NOT
        }); // $.each
    })
    .done(function() {...}

如果 if(){} 是一个函数,那么什么是块?

你在 if

中有一个return false,因此只有当 if 条件不为真并且由 if 控制的块没有运行时,才会到达这两个日志语句。如果块没有运行,则yy没有被分配值。它在范围内,但未初始化。

函数

分配到的变量仅受其作用域的限制,该作用域保证包括声明函数的作用域。

if() { }不是一个函数...这是一个块。它没有出现在您的示例中的原因是,您在日志发生之前return false中断,并且当日志确实发生时,变量仍未定义。

(function () {
  if (true) var x = "if declared variable"; /* block declaration */
  
  document.getElementById('if').innerHTML = x ? x : 'undefined';
  
  (function() {
    var y = "function declared variable";
  })();
  
  if (typeof y != 'undefined')
      document.getElementById('func').innerHTML = y
  else
      document.getElementById('func').innerHTML = 'undefined';
  
})();
if: <span id="if"></span>
<br>
func: <span id="func"></span>