JS宣告提前

2021-09-25 04:42:56 字數 3255 閱讀 3935

js中的宣告提前,變數宣告提前,函式宣告提前,以及宣告提前的順序

console.

log(a)

//?a()

;//?

var a ;

functiona(

)console.

log(a)

;//?

a =6;a

();//?

四個輸出分別是什麼呢?我們來除錯一下,

執行到 a= 6時輸出如下:

最後乙個a();報錯。

接下來我們來分析一下原因

一、什麼是變數宣告提前?

變數在宣告它們的函式體以及這個函式體巢狀的任意函式體內始終可見。說直白點,在宣告乙個變數的前後,你都可以直接使用它,並不會報錯。舉個例子:

(

function

test())()

列印結果:

因為以上**等同於

(

function

test())()

2.什麼是函式宣告提前?

函式宣告提前的原理與變數宣告提前情況類似,需要提醒的是,只有函式宣告格式的函式才會存在函式宣告提前,比如函式表示式,建構函式,都不存在函式宣告提前。

函式建立的三種寫法:

a.函式宣告:function fun(a);(只有這個存在函式宣告提前)

b.函式表示式:var fun = function(a);

c.建構函式:var fun = new function(「a」,console.log(a));

test()

function

test()

此**等同於

function

test()

test

()

再來看看函式表示式
test()

//報錯

console.

log(test)

//undefined

vartest

=function()

test()

//輸出 1

這裡的test被當做變數處理,相當於先宣告乙個變數,再將function賦值給這個變數就,即等同於:

var test 

test()

//此時函式未宣告 所以報錯

console.

log(test)

//已宣告 只是未賦值

test

=function()

test()

//函式已宣告 可以使用

3.變數提公升的順序

既然函式宣告和變數宣告都會提前,那麼到底函式先提公升還是變數先提公升呢?

先來看一段簡單的**:

console.

log(test)

function

test()

var test

為了公平起見我們把變數的位置和函式的位置換一下

console.

log(test)

var test

function

test()

結果:

我們可以看到,兩次列印的結果都是function,也就是說函式的宣告提前會高於變數的宣告提前。

最後讓我們回到

console.

log(a)

//?a()

;//?

var a ;

functiona(

)console.

log(a)

;//?

a =6;a

();//?

此**等同於:

functiona(

)var a;

console.

log(a)

;//funtion 因為函式的提前的優先順序更高a(

);//函式已宣告 所以輸出是10

console.

log(a)

;// function 這裡和上乙個一樣 都是輸出function

a =6;a

();//報錯 因為 已經把6賦值了 a 了,此時a不再是函式

----------------------------- 最後再來看乙個例子 ----------------------------

(學習的時候陰差陽錯打出來的**,想半天給不出解釋,最後問老師才得以解決)

console.

log(

test()

)//???

function

test()

var test

先來看看輸出吧

這裡很容易造成乙個誤區,執行test()時列印test,然後變成變成console.log(test)所以列印undefined???

前面說過了函式宣告優先變數宣告,列印結果不應該為function嗎???

然後我們試著把 var test刪除,

console.

log(

test()

)//???

function

test()

列印結果卻不變,所以問題肯定出在了函式上面。

其實很簡單

test()執行的結果應該是函式的乙個返回值,而console.log中列印的test並不是這個函式執行返回的結果,也就是說console.log(test())列印的應該是函式的返回值。

console.

log(

test()

)function

test()

而我們之前並沒有這個返回值

我的理解是:函式體本身就宣告了返回值 而我們並沒有給這個返回值賦值,所以返回值是undefined。

關於js宣告提前

資料變數宣告提前 var scope golbal function f 宣告提前但不是賦值提前,也就是說上面的 相當於 var scope golbal function f 函式宣告提前 函式有兩種定義方式 1 var f function 2 function f 前一種方式和資料變數一樣,只...

變數宣告提前 總結 js

js在執行時,js變數宣告語句無論出現在何處,都會先於其他 首先被執行。使用var的宣告的變數會提前。先舉個例子看看 console.log a function a var a 3 var b function console.log a 3function a b console.log a 4...

JS函式宣告提前 1

var a 10 function pay pay 7 console.log a 7 函式宣告提前 執行js 前,解析器將當前作用域內宣告的所有變數和函 數都會放到作用域的開始處 1 function pay 會提前宣告 2 var a 10 3 pay 執行函式 4 a 3 a首先會在自己的函式...