繁体   English   中英

无法理解此代码中变量的 scope

[英]not able to understand scope of variable in this code

在此代码中, vid在 function 内部初始化,那么如何在 function 外部使用它(即vid.play()怎么知道vid是使用vid = 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();
}

您已经正确地确定这是一个“可变范围”的问题。 我在您的代码中添加了一些注释,希望它能澄清一些事情。

我建议您查看: 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();
}

不能,它只会看let vid; 多变的。 您有 2 种可能的情况。

  1. init()playVideo()之前调用:

在调用vid.play()时,您的vid变量在init时保存您的视频。


  1. playVideo()init()之前调用:

在调用vid.play()时,您的vid变量将undefined并因此引发错误。

像这样检查vid的值

if (vid) {
 vid.play();
} else {
  alert('Video not initialized')
}

您应该区分变量声明和变量影响(或初始化使用您的话)。 有时这两个动作是同时进行的( let vid = 'value'; )但这不是强制性的。

在 Javascript 中,只要声明了变量,就可以使用它。 然后它的值将是undefined

对于变量的 scope,您的两个函数都可以看到它,因为它是在它之外声明的,请查看第二个片段,如果它已在init function 中声明,它只能由它访问,而不是在它外面可见。

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM