为了账号安全,请及时绑定邮箱和手机立即绑定

无法理解此代码中变量的范围

无法理解此代码中变量的范围

largeQ 2022-09-11 20:16:32
在这个代码中是在函数内部初始化的,所以如何在函数外部使用它(即如何知道它是使用初始化的)。vidvid.play()vidvid = 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();}
查看完整描述

3 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

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


我建议你研究一下: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();

}


查看完整回答
反对 回复 2022-09-11
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

它不能,它只是看变量。这里有2种可能的情况。let vid;

  1. init()在以下之前调用:playVideo()

在调用时,您的变量将视频保存为初始化后的状态。vid.play()vidinit


  1. playVideo()在以下之前调用:init()

在调用时,您的变量将被调用,从而引发错误。vid.play()vidundefined


查看完整回答
反对 回复 2022-09-11
?
德玛西亚99

TA贡献1770条经验 获得超3个赞

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


在 Javascript 中,只要变量已被声明,就可以使用它。然后,其值将为 。undefined


对于变量的范围,你的两个函数都可以看到它,因为它是声明的,看看第二个片段,如果它在函数内部声明,它只能由它访问,而不是在它之外不可见。init


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


查看完整回答
反对 回复 2022-09-11
  • 3 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信