[英]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();
}
您已經正確地確定這是一個“可變范圍”的問題。 我在您的代碼中添加了一些注釋,希望它能澄清一些事情。
// 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 種可能的情況。
init()
在playVideo()
之前調用: 在調用vid.play()
時,您的vid
變量在init
時保存您的視頻。
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.