簡體   English   中英

JavaScript:究竟什么是聲明、定義和初始化變量或函數

[英]JavaScript: What is exactly Declaring, Defining and initialising a variable or a function

我試圖理解什么意味着確切地聲明、定義和初始化變量。

let a;      // If this is a declaration

let a = 22; // and this is initialising

我如何定義一個變量?

我可以初始化一個函數嗎?

我如何定義一個變量?

帶有變量聲明。 定義變量和聲明變量之間沒有區別。 好吧,好吧,有一種定義但不聲明變量的情況:在松散模式下分配給未聲明的標識符,這就是我所說的隱式全局的恐怖,因為它創建了一個沒有任何聲明的全局變量。 不要那樣做。 :-)

我如何聲明一個函數?

在這里對另一個問題的回答列出了在 JavaScript 中創建函數的各種方法。 其中一種方法是函數聲明。

一些簡單的例子,但我懷疑這個問題或那個答案會被刪除:

函數聲明:

function foo() {
}

注意我們沒有在它前面做x = 任何作為表達式的好東西都會使它不再是聲明。

“匿名”函數表達式(盡管有這個術語,但有時會創建帶有名稱的函數):

x = function() { };
//  ^^^^^^^^^^^^^^--- this is the expression

doSomethingWith(function() { });
//              ^^^^^^^^^^^^^^--- this is the expression

命名函數表達式

x = function foo() { };
//  ^^^^^^^^^^^^^^^^^^--- this is the expression

doSomethingWith(function foo() { });
//              ^^^^^^^^^^^^^^^^^^--- this is the expression

訪問器函數初始化器 (ES5+):

obj = {
    get foo() {         // << This is an accessor, specifically a getter
    },                  // <<
    set foo() {         // << This is an accessor, specifically a setter
    }                   // <<
}

箭頭函數表達式(ES2015+)(與匿名函數表達式一樣,不涉及顯式名稱,但可以創建帶名稱的函數); 這些可以是冗長的(帶有{ .. }正文)或簡潔的(沒有{} ):

x = () => { };
//  ^^^^^^^^^--- Verbose arrow function

doSomethingWith(() => { });
//              ^^^^^^^^^--- another verbose arrow function

y = () => expressionGoesHere;
//  ^^^^^^^^^^^^^^^^^^^^^^^^--- Concise arrow function

doSomethingWith(() => expressionGoesHere);
//              ^^^^^^^^^^^^^^^^^^^^^^^^--- another concise arrow function

對象初始化器中的方法聲明(ES2015+)

obj = {
    foo() { // << This is the method declaration
    }       // <<
};

類中的構造函數和方法聲明(ES2015+)

class Example {
    foo() { // << This is the method declaration
    }       // <<
}

我可以初始化一個函數嗎?

您可以使用對函數的引用來初始化變量(或屬性):

let a = function() { };           // Variable
someObject.b = function() { };    // Object property

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM