【问题标题】:Is IF a function in JavaScript?IF 是 JavaScript 中的函数吗?
【发布时间】:2016-02-12 17:26:16
【问题描述】:

我一直在探索 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(){} 是一个函数,那么什么是块?

【问题讨论】:

  • 没有。这不是一个功能。如果它是一个函数。它可能有一个返回值。 var foo = if(...) {... } 是一个明确的语法错误。这是一个关键字。请注意,您在 .each 中的 if() 实际上是在一个函数中:function(i,xdata) ...
  • if 不是函数。是什么让你认为它是一个函数?
  • 您可以在此处阅读语言规范中的声明:ecma-international.org/ecma-262/5.1/#sec-12 :)
  • 谢谢。我现在明白了。

标签: javascript jquery scope


【解决方案1】:

if 中有一个return false,因此只有在 if 条件不成立且 if 控制的块没有运行时才会到达这两个日志语句。如果块没有运行,那么yy 没有被赋值。它在范围内,但未初始化。

【讨论】:

  • return false 甚至在那里工作吗?我知道forEach 没用,不太确定$.each...
  • @Andy 从$.each 返回 false 会停止循环。
【解决方案2】:

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

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>

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多