3 回答
TA贡献1891条经验 获得超3个赞
您已经正确地确定这是一个“可变范围”问题。我已经在你的代码中添加了一些注释,希望它能澄清一些事情。
我建议你研究一下:https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript
// This variable is defined globally. It does not yet have a value, but it is available to everyone at this root level or deeper. All share a reference to the same variable.
let vid;
function init() {
console.log("Page loaded, DOM is ready!");
// This function must run FIRST so we assign the value found here
// but we store it in a variable defined at the root/global scope
// so we are changing a variable that is defined outside this function
vid = document.querySelector("#myPlayer");
vid.ontimeupdate = displayTimeWhileVideoIsPlaying;
}
function playVideo() {
// This will throw an error if the above function does not run first
// Until that runs vid is `undefined`.
// But since the variable that is defined is at the global scope this
// function is able to read the same value that the above function writes.
vid.play();
}
TA贡献1830条经验 获得超3个赞
它不能,它只是看变量。这里有2种可能的情况。let vid;
init()
在以下之前调用:playVideo()
在调用时,您的变量将视频保存为初始化后的状态。vid.play()
vid
init
playVideo()
在以下之前调用:init()
在调用时,您的变量将被调用,从而引发错误。vid.play()
vid
undefined
TA贡献1770条经验 获得超3个赞
您应该区分变量声明和变量影响(或初始化以使用您的单词)。有时两个操作是同时进行的(),但这不是强制性的。let vid = 'value';
在 Javascript 中,只要变量已被声明,就可以使用它。然后,其值将为 。undefined
对于变量的范围,你的两个函数都可以看到它,因为它是声明的,看看第二个片段,如果它在函数内部声明,它只能由它访问,而不是在它之外不可见。init
let vid;
function test(){
console.log(vid); //declared and not initialized
}
function test2(){
console.log(vid2); //not declared (and not initialized)
}
test(); //undefined value (no error)
test2(); //error: not declared
function init(){
let vid;
}
function test3(){
init();
console.log(vid); //declared in another scope
}
test3(); //error: not declared
添加回答
举报