gpt4 book ai didi

javascript - 为什么全局定义的变量是未定义的?

转载 作者:行者123 更新时间:2023-12-03 03:42:59 24 4
gpt4 key购买 nike

我这里有一个简单的函数和一个全局变量。

Why is myname undefined and not the string "global"?

var myname = "global"; // global variable
function func() {
alert(myname); // "undefined"
var myname = "local";
alert(myname); // "local"
}
func();

是否无法引用在该函数范围之外定义的外部变量?在这个全局变量中...

我该如何解决这个问题,这样我就不会得到undefined来自全局变量?

最佳答案

您刚刚偶然发现了一个名为“提升”的 js“功能”

var myname = "global"; // global variable
function func() {
alert(myname); // "undefined"
var myname = "local";
alert(myname); // "local"
}
func();

在此代码中,当您定义 func 时,编译器会查看函数体。它发现您正在声明一个名为 myname 的变量。

Javascript Hoists variable and function declarations, by moving the declaration to the top of the function.

由于提升,您的代码被重写为以下内容。

var myname = "global"; // global variable
function func() {
var myname; //declare local variable and assign it undefined
alert(myname); // "undefined"
myname = "local"; // assign local var myname to "local"
alert(myname); // "local"
}
func();

这“覆盖”了全局变量。如果您想访问函数范围内的全局变量,请使用 this 关键字。

var myname = "global"; // global variable
function func() {
var myname = "local";
alert(this.myname); // "global"
alert(myname); // "local"
}
func();

请注意,这仅适用于调用函数,而不适用于方法或构造函数,因为 this 关键字会根据您调用函数的方式更改其绑定(bind)的内容。

编辑:为了完整性

如果您想在任何上下文中访问全局变量(无论函数类型如何),请声明一个按照惯例您永远不会覆盖的全局变量。

var global = this; // in global scope.
var myname = "global";
var obj = {f: function () {
var myname = "local";
console.log(global.myname);
}};
obj.f(); // "global"

请注意,this 位于方法位置,并且 this 关键字直接引用 obj,因此没有定义 myname。

关于javascript - 为什么全局定义的变量是未定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30469755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com