考虑使用'new'关键字作为'static'的Javascript函数表达式是否正确 [英] Is it right to think of a Javascript Function Expression that uses the 'new' keyword as 'static'
问题描述
我只是想更深入地了解Javascript。
I'm just trying to understand Javascript a little deeper.
我创建了一个'class' gameData
我只想要一个,不需要构造函数,或者实例化。
I created a 'class' gameData
that I only want ONE of, doesn't need a constructor, or instantiated.
所以我就这样创建了它......
So I created it like so...
var gameData = new function () {
//May need this later
this.init = function () {
};
this.storageAvailable = function () {
if (typeof (Storage) !== "undefined") {
return true;
}
else {
return false;
}
};
}
意识到'new'关键字不允许实例化它使它可用LIKE静态类将在C#中。
Realizing that the 'new' keyword doesn't allow it to be instantiated and makes it available LIKE a static class would be in C#.
我是否正确地考虑过这个问题?作为静态?
Am I thinking of this correctly? As static?
推荐答案
不,它不是静态的,因为它仍然有构造函数
属性指向您的匿名函数。在你的例子中,你可以使用
No, it is not static because it still has a constructor
property pointing to your "anonymous" function. In your example, you could use
var gameData2 = new (gameData.constructor)();
重新实例化第二个对象,所以类(实际上是实例)并不是真正的静态 。您基本上泄漏构造函数,可能还有绑定到它的数据。此外,无用的原型对象( gameData.constructor.prototype
)确实已创建并插入的原型链中gameData
,这不是你想要的。
to reinstantiate a second object, so the "class" (instance actually) is not really "static". You are basically leaking the constructor, and possibly the data that is bound to it. Also, a useless prototype object (gameData.constructor.prototype
) does get created and is inserted in the prototype chain of gameData
, which is not what you want.
相反,你可以使用
- 一个简单的对象文字(如 Daff的回答)。这意味着你没有构造函数,没有闭包范围的私有变量(你无论如何都使用过)和没有(自定义)原型。
- (显示)模块模式(如 jAndy的回答)。在那里你有一个 IIFE 来创建闭包范围的变量,并且可以返回任何类型的对象。
- 一个实际的构造函数(class),可以在以后实例化(需要时),并且总是生成相同的单例对象。
- a single, simple object literal (as in Daff's answer). That means you don't have a constructor, no closure-scoped private variables (you have used none anyway) and no (custom) prototype.
- the (revealing) module pattern (as in jAndy's answer). There you'd have an IIFE to create closure-scoped variables, and can return any kind of object.
- an actual constructor ("class") that can be instantiated later (when needed), and yields the same singleton object always.
这就是单例模式的样子:
This is what the singleton pattern would look like:
function GameData() {
if (this.constructor.singleton)
return this.constructor.singleton;
else
this.constructor.singleton = this;
// init:
// * private vars
// * public properties
// ...
}
GameData.prototype.storageAvailable = function () {
if (typeof (Storage) !== "undefined") {
return true;
}
else {
return false;
}
};
var gameData = new GameData();
var gameData2 = new GameData();
gameData === gameData2 === GameData.singleton; // true
然而,原型很无用,因为你只有一个<$ c $的实例C> GAMEDATA 。它只会对继承感兴趣。
Yet, the prototype is quite useless because you have only one instance of GameData
. It would only get interesting with inheritance.
这篇关于考虑使用'new'关键字作为'static'的Javascript函数表达式是否正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!