首页 > 解决方案 > 无法理解此代码中变量的范围

问题描述

在此代码vid中是在函数内部初始化的,那么如何在函数外部使用它(即如何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();
}

标签: javascripthtml

解决方案


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

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

推荐阅读