自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

從一道詭異的JS面試題說“作用域”與“提升”

開發(fā) 前端
有朋友問我一道面試題:一道考察“Hoisting"的面試題目,本篇就這個(gè)問題和大家一起學(xué)習(xí)探討一下!

[[392744]]

 “面試造火箭,工作擰螺絲”。面試題目之詭異,常令人匪夷所思。試看一道考察“Hoisting"的面試題目:

一、提升全局變量 var

  1. var tmp = new Date(); 
  2.  
  3. function f() { 
  4.     console.log(tmp); 
  5.     if (false) { 
  6.         var tmp = "hello"
  7.     } 
  8. f(); 

JS新手往往會(huì)以為將正常打印出日期,而實(shí)際輸出的確是`undefined`!

  1. > var tmp = new Date(); 
  2. function f() { 
  3. ...     console.log(tmp); 
  4. ...     if (false) { 
  5. .....         var tmp = "hello"
  6. .....     } 
  7. ... } 
  8. > f(); 
  9. undefined  

這是因?yàn)樵诤瘮?shù)f()的內(nèi)部,var被提升到定義域的頂部,實(shí)際執(zhí)行為:

  1. var tmp = new Date(); 
  2.  
  3. function f() { 
  4.     var tmp;// 提升到這里,將全局的tmp覆蓋了。var默認(rèn)賦值為undefined 
  5.     console.log(tmp); 
  6.     if (false) { 
  7.         var tmp = "hello"
  8.     } 
  9. f(); 

也就是說var不僅提升,而且將tmp初始化賦值為undefined。

二、如何才能正常輸入日期呢?

解決方案是將global-scope的var替換為block-scope的let:

  1. var tmp = new Date(); 
  2.  
  3. function f() { 
  4.     //var tmp;// 提升到這里,將全局的tmp覆蓋了。var默認(rèn)賦值為undefined 
  5.     console.log(tmp); 
  6.     if (false) { 
  7.         let tmp = "hello"
  8.     } 
  9. f(); 
  10. // 2021-04-02T10:52:30.983Z 

這是因?yàn)閘et定義的是local-variable.

三、TDZ臨時(shí)DeadZones

更加詭異的案例,來單獨(dú)看let:

  1. var tmp = new Date(); 
  2.  
  3. function f() { 
  4.     console.log(tmp); 
  5.     let tmp = "hello"
  6.  
  7. f(); 

你原以為將會(huì)如常打印出時(shí)間,但卻報(bào)錯(cuò)tmp未定義。

  1. ReferenceError: Cannot access 'tmp' before initialization 

這是因?yàn)?tmp 被提升,其實(shí)際執(zhí)行為:

  1. var tmp = new Date(); 
  2.  
  3. function f() { 
  4.     let tmp; // 提升在這里 
  5.     console.log(tmp); 
  6.     let tmp = "hello"
  7.  
  8. f(); 

然而區(qū)別于var的是,tmp僅僅被提升,卻不會(huì)被自動(dòng)賦值為undefined,因此會(huì)報(bào)錯(cuò)`ReferenceError`.

該問題就是傳說中的TDZ (temporal dead zone)。解決方案也簡單,就是將所有的let或者const等全部都寫到最上面。

 

責(zé)任編輯:姜華 來源: 今日頭條
相關(guān)推薦

2021-03-27 10:59:45

JavaScript開發(fā)代碼

2024-10-11 17:09:27

2018-04-26 11:23:01

Linuxfork程序

2022-02-08 18:09:20

JS引擎解析器

2011-05-23 11:27:32

面試題面試java

2018-03-06 15:30:47

Java面試題

2009-08-11 10:12:07

C#算法

2023-02-04 18:24:10

SeataJava業(yè)務(wù)

2009-08-11 14:59:57

一道面試題C#算法

2021-05-31 07:55:44

smartRepeatJavaScript函數(shù)

2009-08-11 15:09:44

一道面試題C#算法

2017-11-21 12:15:27

數(shù)據(jù)庫面試題SQL

2022-04-08 07:52:17

CSS面試題HTML

2023-08-01 08:10:46

內(nèi)存緩存

2021-03-16 05:44:26

JVM面試題運(yùn)行時(shí)數(shù)據(jù)

2021-10-28 11:40:58

回文鏈表面試題數(shù)據(jù)結(jié)構(gòu)

2020-11-06 09:05:18

前端web開發(fā)

2011-03-02 10:58:16

SQL server入門面試題

2015-09-02 14:09:19

面試題程序設(shè)計(jì)

2017-03-10 09:33:16

JavaScript類型
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)