对不起,如果我误用了某些术语或定义。 示例:
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
应该基本上可以从任何地方访问。这是什么问题?
答案 0 :(得分:3)
否,因为您是在匿名函数内部且仅在可以访问thoose变量的函数中定义testFirst
和testSecond
变量。
要全局访问,您可以执行以下操作:
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);
}
答案 1 :(得分:1)
因为const
是作用域。声明前不存在。考虑一个例子:
console.log(value);
var value = 42;
/**
*JavaScript engine must "hoist" that `var` declaration to top of file, so it ends up being:
var value;
console.log(value);
value = 42
*/
使用const不会发生:
console.log(value);
const value = 42; // No "hoisting"
现在,这是另一个例子。
function logValue() {
console.log(value);
}
const value = 42;
logValue();
发生了什么事:
声明了一个功能。
在全球范围内创建了一个value
。
我们称之为函数-它在全局范围内找到了值。
让我们现在使用您的版本:
function logValue() {
console.log(value);
}
function run(){
const value = 42;
// testFirst now exists _but only in the scope of the run function!
// logValue is not in that scope!
logValue();
}
run();
最后,让我们尝试其他事情:
function run(){
function logValue() {
console.log(value);
}
const value = 42;
// testFirst now exists _but only in the scope of the run function!
// logValue is not in that scope!
logValue();
}
run();
现在该功能在相同范围内。因此,如果将类移到创建实例的同一个onLoad函数中,它将起作用。