JavaScript 中定義函數用 var foo = function () {} 和 function foo()區別介紹,varfoo

來源:互聯網
上載者:User

JavaScript 中定義函數用 var foo = function () {} 和 function foo()區別介紹,varfoo

某天寫代碼突然縣道這個問題,順勢總結一波

JavaScript 函數和變數聲明的“提前”(hoist)行為

簡單的說 如果我們使用 匿名函數

var a = {}

這種方式, 編譯後變數聲明a 會“被提前”了,但是他的賦值(也就是a)並不會被提前。

也就是,匿名函數只有在被調用時才被初始化。

如果使用

function a () {};

這種方式, 編譯後函式宣告和他的賦值都會被提前。

也就是說函式宣告過程在整個程式執行之前的預先處理就完成了,所以只要處於同一個範圍,就可以訪問到,即使在定義之前調用它也可以。

看一個例子

function hereOrThere() { //function statement  return 'here';}console.log(hereOrThere()); // alerts 'there'function hereOrThere() {  return 'there';}

我們會發現alert(hereOrThere) 語句執行時會alert('there')!這裡的行為其實非常出乎意料,主要原因是JavaScript 函式宣告的“提前”行為,簡而言之,就是Javascript允許我們在變數和函數被聲明之前使用它們,而第二個定義覆蓋了第一種定義。換句話說,上述代碼編譯之後相當於

function hereOrThere() { //function statement return 'here';}function hereOrThere() {//申明前置了,但因為這裡的申明和賦值在一起,所以一起前置 return 'there';}console.log(hereOrThere()); // alerts 'there'

我們期待的行為

var hereOrThere = function () { // function expression  return 'here';};console.log(hereOrThere()); // alerts 'here'hereOrThere = function () {  return 'there';};

這段程式編譯之後相當於:

var hereOrThere;//申明前置了hereOrThere = function() { // function expression return 'here';};console.log(hereOrThere()); // alerts 'here'hereOrThere = function() { return 'there';};

總結

以上所述是小編給大家介紹的JavaScript 中定義函數用 var foo = function () {} 和 function foo()區別介紹,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.