javascript - 无法理解此代码中变量的范围
问题描述
在此代码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();
}
解决方案
您已经正确地确定这是一个“可变范围”的问题。我在您的代码中添加了一些注释,希望它能澄清一些事情。
// 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();
}
推荐阅读
- powershell - 在 PowerShell 脚本中调用其他 PowerShell 脚本
- postgresql - Sequelize throwing:“关系“用户”不存在”
- php - 如何在 Moodle 3.5 中正确地需要依赖插件
- html - 如何在外部 CSS 文件 (.css) 中设置 lang 全局属性
- java - 使用 JNI 调用从 Cpp 返回字符串数组的 Java 方法
- javascript - 在Javascript中唯一更新数组中的对象时,对象的值都在变化
- r - R markdown 多个选项卡不会在 HTML 中生成
- python-3.x - 使用 Python 编辑 JSON 响应
- spring - Docusign EventNotification CSRF 保护
- php - 正则表达式 - 如果 PHP preg_match_all 有特定的单词和不区分大小写,则匹配整行