Home > Web Front-end > JS Tutorial > Is a JavaScript Function Expression with `new` Truly Static?

Is a JavaScript Function Expression with `new` Truly Static?

Susan Sarandon
Release: 2024-12-20 12:55:19
Original
483 people have browsed it

Is a JavaScript Function Expression with `new` Truly Static?

Is a Javascript Function Expression Using 'new' Keyword Truly Static?

In an attempt to create a static-like class in Javascript without using a constructor or instantiation, code was written as such:

var gameData = new function () {
    //May need this later 
    this.init = function () { };

    this.storageAvailable = function () {
        if (typeof (Storage) !== "undefined") {
            return true;
        }
        else {
            return false;
        }
    };
}
Copy after login

The assumption is that the 'new' keyword prevents instantiation and makes the function expression behave like a static class. However, this is not entirely accurate.

Understanding the 'Static' Concept in Javascript

In Javascript, a static property or method is not bound to an instance of a class. It belongs to the class itself, regardless of whether any instance exists. Static members are typically shared by all instances of a class.

Limitations of the Function Expression Approach

Despite the 'new' keyword, the function expression still has a constructor property. This means it can be reinstated using the following code:

var gameData2 = new (gameData.constructor)();
Copy after login

This creates a separate instance of the function expression, negating the intended static behavior. Additionally, the prototype chain contains a useless prototype object for the function expression.

Alternatives to 'Static' Implementation in Javascript

To achieve true static behavior, consider these alternatives:

  • Object Literal: Use a simple object literal to define properties and methods without a constructor.
  • Revealing Module Pattern: Enclose the object literal in an IIFE (Immediately Invoked Function Expression) to create closure-scoped variables.
  • Constructor 'Class': Define a constructor function that returns the same singleton object upon instantiation.

The above is the detailed content of Is a JavaScript Function Expression with `new` Truly Static?. 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