Home >Web Front-end >JS Tutorial >Does `new` with JavaScript Function Expressions Create Static Behavior?
Function Expressions with 'new' Keyword: Unveiling the Static Nature
In JavaScript, understanding the behavior of function expressions with the 'new' keyword is crucial. Consider the following code:
var gameData = new function () { // Function expressions require no constructor this.storageAvailable = function () { ... }; };
It's important to note that the 'new' keyword in this case does not imply instantiation or allow for multiple instances to be created. Instead, it simply executes the function expression and assigns the resulting anonymous object to the 'gameData' variable.
The Misconception of Static Behavior
The concept of static behavior in C# may lead to the misconception that the function expression in JavaScript also behaves statically. However, this is inaccurate. The 'new' keyword here does not prevent the creation of a second object:
var gameData2 = new (gameData.constructor)(); // Reinstantiation is possible
Additionally, the function expression still has a constructor property pointing to the anonymous function, which can be accessed using 'gameData.constructor'. This defeats the purpose of a true static class.
Alternatives to Static Behavior
If the intent is to create a single, non-instantiable object, there are more appropriate alternatives to using function expressions with 'new':
In conclusion, function expressions with 'new' keywords in JavaScript do not exhibit static behavior as they can be instantiated multiple times and have a public constructor property accessible through 'gameData.constructor'. For true static behavior, consider adopting alternative approaches such as object literals, revealing module patterns, or the singleton pattern.
The above is the detailed content of Does `new` with JavaScript Function Expressions Create Static Behavior?. For more information, please follow other related articles on the PHP Chinese website!