猿问

初始化之前如何访问 timeoutID?

function addNew() {

    let id = setTimeout( function() {console.log(id)}, 0)

}


addNew()


初始化之前如何访问 id?我认为这与第二个代码片段没有什么不同。


function customTimeout(fn) {

    fn()

    return 32423

}


function addNew() {

    let id = customTimeout( function() {console.log(id)})

}


addNew()


慕的地10843
浏览 172回答 3
3回答

隔江千里

尚未初始化的变量不能直接被运行到变量初始化之前的行(该行)直接引用let id =,但仍然允许尚未调用的函数引用内部变量。在第一个代码片段中,setTimeout回调不会运行,直到该let id =行完成id变量的初始化,因此这是允许的。在第二个片段中,传递给的回调在in 行完成初始化之前customTimeout运行,因此不允许这样做。let id =addNewid// Permitted:const fn = () => {  // do something with someVariable  console.log(someVariable);};// The above is finelet someVariable = 'foo';// just make sure fn is called ONLY AFTER `let someVariable;` runsfn();// Not permitted:const fn = () => {  console.log(someVariable);};fn();let someVariable = 'foo';// Permitted, since fn is called asynchronously:function customTimeout(fn) {    Promise.resolve().then(fn);    return 32423}function addNew() {    let id = customTimeout( function() {console.log(id)})}addNew()// Permitted, since fn is called asynchronously:function customTimeout(fn) {    setTimeout(fn);    return 32423}function addNew() {    let id = customTimeout( function() {console.log(id)})}addNew()// Permitted, since fn is called after `id` has finished being assigned to:function customTimeout(fn) {    return [12345, fn];}function addNew() {    let [id, fn] = customTimeout( function() {console.log(id)})    fn();}addNew()

侃侃尔雅

当您调用时setTimeout(即使超时0),回调不会立即运行。它被放入堆栈中以便在将来的某个时刻运行。因此,在第一个示例中,您将设置id为 . 返回的“timeoutID” setTimeout。当将来(异步)运行回调时,id是否存在并且回调可以看到它。在第二个示例中,您将回调传递给customTimeout. 在该函数返回任何内容之前,会运行回调。它立即(同步)运行,并在回调运行后customTimeout返回一个值。由于该值是在函数运行后返回的,因此函数看不到它。

catspeake

看例子,希望你能理解。function addNew() {&nbsp; &nbsp; let id = setTimeout(&nbsp; // <-- 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function() { // <-- 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(id) // <--- here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; , 0)}addNew()/** It will not work.*/function addOld() {&nbsp; &nbsp; console.log(id)&nbsp; &nbsp; let id = 2;}addOld()
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答