JavaScript:什么是声明,定义和初始化变量或函数

时间:2018-05-15 16:18:33

标签: javascript function

我试图理解什么意味着确切地声明,定义和初始化变量。

let a;      // If this is a declaration

let a = 22; // and this is initialising

我如何定义变量?

我可以初始化一个函数吗?

1 个答案:

答案 0 :(得分:2)

  

我如何定义变量?

使用变量声明。定义变量和声明变量之间没有区别。嗯,好吧,有一种情况是定义但没有声明变量:在松散模式下分配一个未声明的标识符,这就是我所谓的The Horror of Implicit Globals,因为它创建了一个没有任何声明的全局变量。不要那样做。 : - )

  

我如何声明一个函数?

我对另一个问题的回答here列出了在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