In object-oriented programming languages like Java, static variables are commonly used to declare members that belong to a class and are shared by all instances of that class. This article explores how this concept is implemented in JavaScript.
In JavaScript, which follows a prototype-based inheritance model, functions serve as constructors. Static properties can be defined within the constructor function itself, as they are associated with the function object.
function MyClass() { // Private variable var privateVariable = "foo"; // Public variable this.publicVariable = "bar"; // Public method this.privilegedMethod = function() { alert(privateVariable); }; } // Static variable shared by all instances MyClass.staticProperty = "baz";
In this example, staticProperty is defined within the MyClass function and is accessible across all instances of the class.
ES6 introduced the class keyword for declaring classes, providing syntax sugar for prototype-based inheritance. Static properties and methods can be defined using the static keyword.
class MyClass { constructor() { // Private variable const privateVariable = 'private value'; // Public property this.publicVariable = 'public value'; // Public method with access to private variable this.privilegedMethod = function() { console.log(privateVariable); }; } // Prototype methods publicMethod() { console.log(this.publicVariable); } // Static property shared by all instances static staticProperty = 'static value'; // Static method static staticMethod() { console.log(this.staticProperty); } }
Here, staticProperty and staticMethod are defined as static members of the MyClass class, making them accessible without creating an instance.
The above is the detailed content of How are Static Variables Declared and Used in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!