📜  JavaScript 中静态和常量的区别

📅  最后修改于: 2022-05-13 01:56:22.416000             🧑  作者: Mango

JavaScript 中静态和常量的区别

静态变量 JavaScript 中的静态变量基本上是类的一个属性,它不用于类的对象,而是用于类本身。此静态变量存储在内存的数据段中,其值在该特定类中创建的所有对象/实例之间共享。要将变量/函数声明为静态,我们使用了“静态”关键字。在静态变量的情况下,它的值是在运行时本身设置的,它是一个全局值,可以被类的实例使用。

示例:在下面的代码中,我们在类 z 中声明了一个静态方法,并使用文档 .write()方法将其打印出来。

JavaScript


JavaScript


输出:

常量: JavaScript 中的常量变量是具有常量或固定值且保持不变的变量,即。这在整个程序中都不会改变。一旦声明,就不可能对其值进行任何形式的修改。如果程序员试图修改它的值,编译器会显示一个错误,这是因为一旦我们将一个变量声明为常量,它就会告诉编译器这是一个固定值,应该阻止对其进行任何更改。

示例:下面是const关键字在 JavaScript 中的实现。在下面的代码中,我们将变量声明为const并使用document.write()方法,我们显示了它的值。

JavaScript

     

输出:

8

静态和常量的区别:

                                               Static                                                       Constant
The static methods are basically utility functions creating or making a copy of an object.The const variable is basically used for declaring a constant value that cannot be modified.
A static keyword is been used to declare a variable or a method as static.A const keyword is been used to assign a constant or a fixed value to a variable.
In JavaScript, the static keyword is used with methods and classes too.In JavaScript, the const keyword is used with arrays and objects too.
The value of a static variable can be modified.The value of the constant variable cannot be modified.
Static is a storage specifier.Const/Constant is a type qualifier.
Static can be assigned for reference types and set at run time.Constants are set at compile-time itself and assigned for value types only.