Home >Web Front-end >JS Tutorial >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; } }; }
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)();
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:
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!