Home > Web Front-end > JS Tutorial > How Do I Create and Use Static Variables in JavaScript?

How Do I Create and Use Static Variables in JavaScript?

DDD
Release: 2024-12-02 05:27:12
Original
847 people have browsed it

How Do I Create and Use Static Variables in JavaScript?

Deciphering Static Variables in JavaScript

In JavaScript, objects are first-class citizens, meaning they can possess properties and methods. If you're familiar with class-based, statically typed languages like Java, you've likely encountered the concept of creating variables and methods associated with types rather than instances.

To accomplish this in JavaScript, let's employ a "classical" approach utilizing constructor functions:

function MyClass () { 
  var privateVariable = "foo";  // Private variable 

  this.publicVariable = "bar";  // Public variable 

  this.privilegedMethod = function () {
    alert(privateVariable);
  };
}
Copy after login

Here, staticProperty is defined directly on the MyClass object, making it accessible to all instances created with the constructor. However, it's crucial to remember that it has no direct link to those instances.

ES6 Classes and Static Variables

With the introduction of ES6 classes, declaring static variables and methods becomes a breeze:

class MyClass {
  constructor() {
    this.publicVariable = 'public value'; 
  }

  publicMethod() {
    console.log(this.publicVariable);
  }

  // Static properties shared by all instances
  static staticProperty = 'static value';

  static staticMethod() {
    console.log(this.staticProperty);
  }
}
Copy after login

In this example, staticProperty and staticMethod are effortlessly defined using the static keyword, allowing them to be accessed through the class itself.

Understanding the nuances of static variables in JavaScript is essential for constructing robust and efficient code, especially when leveraging concepts from other programming paradigms.

The above is the detailed content of How Do I Create and Use Static Variables 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template