gpt4 book ai didi

javascript - 为什么在 windows.onload 事件处理程序中创建的范例不是全局可见的?

转载 作者:行者123 更新时间:2023-11-29 10:01:30 24 4
gpt4 key购买 nike

如果我误用了某些术语或定义,请提前致歉。 示例:

class First  {
constructor(){
this.value = 5;
}
}

class Second {
constructor(){
this.value = testFirst.value
}
}


window.onload = function(){

const testFirst = new First();
const testSecond = new Second(); // testFirst is not defined
}

我认为如果 window.onload 事件的作用域是 window,并且在函数执行后用 var 声明的变量仍然存在,那么testFirst 应该基本上可以从任何地方访问。这里有什么问题?

最佳答案

不,因为您在匿名函数内定义了 testFirsttestSecond 变量,并且仅在可以访问这些变量的函数中。

为了全局访问,你可以这样做:

var testFirst;
var testSecond;

window.onload = function(){

testFirst = new First();
testSecond = new Second();
}

window.onload = function(){

window.testFirst= new First();
window.testSecond = new Second();
}

具体来说,对于您的情况,请遵循第一个示例的工作脚本:

var testFirst;
var testSecond;

class First {
constructor(){
this.value = 5;
}
}

class Second {
constructor(){
this.value = testFirst.value
}
}


window.onload = function(){
testFirst = new First();
testSecond = new Second(); // testFirst is not defined
console.log(testSecond.value);
}

对于第二种情况:

class First  {
constructor(){
this.value = 5;
}
}

class Second {
constructor(){
this.value = window.testFirst.value
}
}


window.onload = function(){
window.testFirst = new First();
window.testSecond = new Second(); // testFirst is not defined
console.log(testSecond.value);
}

另外,如果你定义一个没有 var 的变量,让你的 const 标签,这个变量也将成为全局变量:

class First  {
constructor(){
this.value = 5;
}
}

class Second {
constructor(){
this.value = testFirst.value
}
}


window.onload = function(){
testFirst = new First();
testSecond = new Second(); // testFirst is not defined
console.log(testSecond.value);
}

关于javascript - 为什么在 windows.onload 事件处理程序中创建的范例不是全局可见的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56061559/

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