无法理解函数's的行为

Not able to understand the function's behavior

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

无法理解函数的行为

function Animal() {
    console.log("showing an empty string: " + name);
    console.log("showing not defined: " + other);
}
Animal("Tommy");

由于您的函数不接受任何参数,因此执行

console.log("showing an empty string: " + name);

将导致

showing an empty string:

执行时

console.log("showing not defined: " + other);

将导致错误"ReferenceError:other is not defined"。

这种行为是因为您使用全局变量,并且每个窗口都定义了名称。默认情况下为"(空字符串)。

所以,如果您打开控制台并编写window.name,您将获得""如果你写window.other,你会得到undefined

因此,每个window都有一个主要由window.name访问的name属性。

所以当你调用这个函数时,第一行是打印

showing an empty string:

因为通常name是一个空变量,而在第二行中没有定义变量other,所以它抛出了错误。