Javascript 无法理解此代码中变量的范围
在此代码中,Javascript 无法理解此代码中变量的范围,javascript,html,Javascript,Html,在此代码中,vid在函数内部初始化,因此如何在函数外部使用它 (即vid.play()如何知道vid是使用vid=document.querySelector(“#myPlayer”)初始化的) 它不能,它只需查看let vid变量。这里有两种可能的情况 在播放视频()之前调用init(): 调用vid.play()时,您的vid变量保存您的视频 asinit初始化了它 在init()之前调用playVideo(): 调用vid.play()时,您的vid变量将是未定义的,因此会抛出一个错误。
vid
在函数内部初始化,因此如何在函数外部使用它
(即vid.play()
如何知道vid
是使用vid=document.querySelector(“#myPlayer”)
初始化的)
它不能,它只需查看
let vid代码>变量。这里有两种可能的情况
在播放视频()之前调用init()
:
调用vid.play()
时,您的vid
变量保存您的视频
asinit
初始化了它
在init()之前调用playVideo()
:
调用vid.play()
时,您的vid
变量将是未定义的
,因此会抛出一个错误。像这样检查vid
的值
if (vid) {
vid.play();
} else {
alert('Video not initialized')
}
您已经正确地确定这是一个“可变范围”的问题。我在你的代码中添加了一些注释,希望它能澄清一些问题
我建议你研究一下:
您应该区分变量声明和变量做作(或初始化)。有时两个操作同时执行(让vid='value';
),但这不是强制性的
在Javascript中,只要声明了变量,就可以使用它。然后,其值将为未定义的
对于变量的作用域,您的两个函数都可以看到它,因为它被声明在它的外部。请看第二个代码段,如果它在init
函数内部声明,那么它只能被它访问,在它外部不可见
let-vid;
功能测试(){
console.log(vid);//已声明但未初始化
}
函数test2(){
console.log(vid2);//未声明(也未初始化)
}
test()//未定义的值(无错误)
test2()//错误:未声明
您在哪里调用了init()
方法?不应该将vid作为参数传递给init函数,以便在函数内部初始化全局vid。您提供的链接没有涵盖此类声明和初始化@蔡斯,没错。它有一个称为变量范围的完整部分
,正好涵盖了这一点。在“如果你应该把它作为一个论点通过”方面。这是偏好的问题。您在原始问题中所写的内容是完全合法的,如果按照正确的顺序执行,将可以正常工作。但我可能同意这不是一个“理想”的实现。
if (vid) {
vid.play();
} else {
alert('Video not initialized')
}
// 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();
}