为什么我的javascript函数没有抛出错误?

时间:2014-12-29 04:03:22

标签: javascript function global-variables evaluate window-object

在调用我的函数之后,我惊讶于我的函数没有因为变量而导致错误。使用未在函数范围内定义的变量。

我的问题: 为什么我的函数没有抛出未定义的错误等?不应该抛出错误,因为"长度"不在我的函数参数中吗?我知道如果我切换"长度"到"身高"它会起作用。

如果有人能够解释javascript如何逐步解释这个功能,那将对我有所帮助。这是我的代码:

function areaRectangle(width, height) {
   aRectangle = width * length;
   console.log("The area of the rectangle is: " + aRectangle);
}
areaRectangle(10, 7); # The area of the rectangle is: 0

7 个答案:

答案 0 :(得分:6)

因为它使用的window.length属性恰好是0而不是参数或变量。

答案 1 :(得分:5)

这取决于您执行此功能的环境。

如果您在浏览器中执行此操作,似乎全局上下文中有一个长度属性,其值为数值。当您在控制台中执行函数并尝试访问长度时,由于函数中未定义长度,因此JavaScript引擎将在全局上下文中查找length变量(因为关闭)。

如果您在Node中执行此操作,您会注意到抛出错误,因为Node中的全局上下文没有长度属性。

答案 2 :(得分:1)

您尚未在函数内部本地定义长度变量。因此,当您调用此函数时,它会查找其父作用域以查找length变量的值。

假设此函数在全局范围内定义,那么它将查找window对象以查找length的值。在这种情况下,window.length是指当前窗口中iframe的数量。您可以阅读有关window.length here的更多信息:

话虽如此,我们可以通过修改您的原始功能来解决这个问题。由于您的函数正在尝试计算矩形的面积,我们需要修改您的原始函数,以便使用您的两个参数计算距离。我建议你做以下事情:

function areaRectangle(width, height) {
  aRectangle = width * height; // notice we changed the second variable to height
  console.log("The area of the rectangle is: " + aRectangle);
}
areaRectangle(10, 7); // This will result in 70.

答案 3 :(得分:1)

当您未在当前代码块中声明它时,您可以访问最近的相关父作用域变量,因此当您引用length时,如果不存在声明的变量,则将其解析为全局范围在大多数执行环境中。在上下文为window的浏览器中,您实际上是引用window.length

认识到答案有点复杂,下面是一个如何解析本地或父范围变量的例子。

如果你这样做了,



<script>
    var length = "potato";
    function areaRectangle(width, height) {
        aRectangle = width * length;
        console.log("The area of the rectangle is: " + aRectangle);
    }
    areaRectangle(10, 7); // My number results in 0
</script>
&#13;
&#13;
&#13;

你会在控制台中得到这个;

  

矩形区域为:NaN

所以如果你这样做了,

&#13;
&#13;
<script>
    var length = "potato";
    function areaRectangle(width, height) {
		var length = height;
        aRectangle = width * length ;
        console.log("The area of the rectangle is: " + aRectangle);
    }
    areaRectangle(10, 7); // results is 70
</script>
&#13;
&#13;
&#13;

你会在控制台中得到这个:

  

矩形区域为:70

这是因为变量length在本地或另一个更近的可见范围内声明。

在您的代码中,变量被绑定到全局对象(浏览器中为window),从而生成window.length

答案 4 :(得分:1)

length派生自window.length,这是一个属性,用于定义给定窗口上下文中有多少帧。 0 =无帧,1 = 1帧,N = N帧。

https://developer.mozilla.org/en-US/docs/Web/API/Window.length

这不应与Object.length的给定属性混淆,因为window继承自Objecthttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Properties)。

答案 5 :(得分:0)

目前

length0。它也恰好存在于全球范围内(window)。我想你可能会混淆你的变量名。

您可以使用名为length的变量作为参数,但是您不必在此处执行此操作,因此它使用全局范围内的变量。

这就是你想要的:

function areaRectangle(width, height) 
{
    aRectangle = width * height;

    console.log("The area of the rectangle is: " + aRectangle);
}

areaRectangle(10, 7);

答案 6 :(得分:0)

您尝试使用use strict

function areaRectangle(width, height) {
  'use strict';
  aRectangle = width * length;
  console.log("The area of the rectangle is: " + aRectangle);
}
areaRectangle(10, 7);
Open console...