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

How Can I Create Static Variables in JavaScript?

Susan Sarandon
Release: 2024-12-04 14:11:11
Original
343 people have browsed it

How Can I Create Static Variables in JavaScript?

Creating Static Variables in JavaScript

In contrast to statically typed languages where variables are inherently tied to a type, JavaScript's dynamic typing allows for the creation of variables that exist independently of any instance.

Classical Approach with Constructor Functions

JavaScript's prototype-based model enables the definition of public and private variables through constructor functions. Private variables are scoped within the constructor function, while public variables are accessible to all instances.

Example:

function MyClass() {
  var privateVariable = "foo";
  this.publicVariable = "bar";
}

MyClass.staticProperty = "baz";
Copy after login

In this example, staticProperty is a static variable associated with the MyClass object, accessible across all instances.

ES6 Classes

ES6 introduces the class syntax, providing a more class-based approach. Static properties and methods can be defined using the static keyword.

Example:

class MyClass {
  constructor() {
    this.publicVariable = "bar";
  }

  static staticProperty = "baz";
}
Copy after login

Additional Considerations

While JavaScript does not natively support true static class variables like in Java, the provided methods effectively create variables that are shared across all instances without the need for direct instance referencing.

The above is the detailed content of How Can I Create 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template