无法理解此代码中变量的范围

在这个代码中是在函数内部初始化的,所以如何在函数外部使用它(即如何知道它是使用初始化的)。vidvid.play()vidvid = document.querySelector("#myPlayer")


window.onload = init;


let vid;

function init() {

  console.log('page loaded, DOM is ready');

  vid = document.querySelector('#myPlayer');

  vid.ontimeupdate = displayTimeWhileVideoIsPlaying();

}


function playVideo() {

  vid.play();

}


largeQ
浏览 121回答 3
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();}

牛魔王的故事

它不能,它只是看变量。这里有2种可能的情况。let vid;init()在以下之前调用:playVideo()在调用时,您的变量将视频保存为初始化后的状态。vid.play()vidinitplayVideo()在以下之前调用:init()在调用时,您的变量将被调用,从而引发错误。vid.play()vidundefined

德玛西亚99

您应该区分变量声明和变量影响(或初始化以使用您的单词)。有时两个操作是同时进行的(),但这不是强制性的。let vid = 'value';在 Javascript 中,只要变量已被声明,就可以使用它。然后,其值将为 。undefined对于变量的范围,你的两个函数都可以看到它,因为它是声明的,看看第二个片段,如果它在函数内部声明,它只能由它访问,而不是在它之外不可见。initlet 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 declaredfunction init(){    let vid;}function test3(){    init();    console.log(vid); //declared in another scope}test3(); //error: not declared
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript