亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Javascript 中使用閉包的函數的意外輸出

在 Javascript 中使用閉包的函數的意外輸出

翻閱古今 2021-11-18 20:50:09
const run = initialize;run(1);run(1);run(1);function initialize(index) {    console.log('runs only once');    return function(index) {        console.log('useless code to use closure to make sure initialize only runs once');        return index;    }}這不起作用,但我不確定為什么,因為下面的代碼按預期工作,并且只在外部函數中運行一次代碼,同時多次運行內部函數。const getIndex = bigStuff();getIndex(500);getIndex(600);getIndex(700);function bigStuff(index) {    const myArray = new Array(300).fill('3');    console.log('created once');    return function(index) {        console.log('calling several times');        return myArray[index];    }}第二段代碼返回:created oncecalling several timescalling several times calling several times 雖然第一塊代碼返回:runs only onceruns only onceruns only once有人可以向我解釋 Javascript 引擎在后臺做什么嗎?因為我覺得當你使用閉包時,輸出會根據內部和外部函數內部的內容而有所不同。
查看完整描述

1 回答

?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

const run = initialize()


run(1); 


run(1); 


run(1); 


function initialize(index) {



    console.log('runs only once');


    return function(index) { 


        console.log('useless code to use closure to make sure initialize only runs once');


        return index;


    } 


}


通過將第一行更改為實際調用initialize并返回一個函數,上面按預期運行


查看完整回答
反對 回復 2021-11-18
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號