JS的變數提公升

2022-05-18 17:51:54 字數 1182 閱讀 4780

var宣告的變數。

console.log(v1);

var v1 = 100;

function

foo()

foo();

console.log(v1);

輸出結果:

//

undefined

//undefined

//200

//100

宣告函式的兩種方式:

function bar () {}    //

函式宣告式

var foo = function () {} //

函式字面量式,這個和變數提公升的結果是一樣的,函式只是乙個具體的值

但是函式宣告式的提公升現象和變數提公升略有不同,具體如下:

console.log(bar);

function

bar ()

輸出結果:

執行順序相當於:

function

bar ()

console.log(bar);

函式提公升是整個**塊提公升到它所在的作用域的最開始執行

函式提公升要比變數提公升的優先順序要高一些,且不會被變數宣告覆蓋,但是會被變數賦值之後覆蓋。

console.log(a);    //

f a()

console.log(a()); //

10var a = 3;

function

a()

console.log(a)

// 3

a = 6;

console.log(a());

//報錯:a is not a function;

執行順序相當於

var a =funtion () 

vara;

console.log(a);

//f a()

console.log(a()); //

10a = 3;

console.log(a) //3

a = 6;

console.log(a());

//報錯:a() is not a function;

js變數提公升

在了解變數提公升之前,應該先了解一下js到底是一種什麼型別的語言,他的執行機制又是怎樣的.console.log global undefined var global global console.log global global function fn fn 可以看出來 變數提公升只是將變數提...

js變數提公升

var a 100 functionf console.log a f undefined 200var a 100 functionf f console.log a 100如果你習慣了強型別語言的程式設計方式,那麼看到上述輸出結果你肯定會大吃一驚。我們來看一下c 的乙個例子 include us...

JS變數提公升

在當前作用域中,js 自上而下執行之前,瀏覽器首先會把所有的帶var function關鍵字的進行提前宣告 定義。注意宣告和定義的區別 宣告 declare var num 在當前作用域中吼一嗓子我有num這個名字了。定義 define num 12 把宣告的名字賦值。console.log a u...