Home > Web Front-end > JS Tutorial > How are Static Variables Declared and Used in JavaScript?

How are Static Variables Declared and Used in JavaScript?

Mary-Kate Olsen
Release: 2024-12-06 17:14:14
Original
1001 people have browsed it

How are Static Variables Declared and Used in JavaScript?

Declaring Static Variables in JavaScript

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.

Static Variables in ES5

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";
Copy after login

In this example, staticProperty is defined within the MyClass function and is accessible across all instances of the class.

Static Variables in ES6 Classes

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);
  }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template