如何在EcmaScript 5中添加静态成员

Max*_*eng 7 javascript ecmascript-5

我想在EcmaScript 5 JavaScript中为类添加静态函数.我的类定义如下:

var Account = {};

Object.defineProperty(Account, 'id', {
    value : null
});
Run Code Online (Sandbox Code Playgroud)

我会创建一个这样的新实例:

var theAccount = Object.create(Account);
theAccount.id = 123456;
Run Code Online (Sandbox Code Playgroud)

现在我想在Account类中添加一个静态函数.如果我Account使用构造函数和prototype类似的属性创建了类:

var Account = function () {
    this.id = null;
};
Run Code Online (Sandbox Code Playgroud)

......我可以这样做:

Account.instances = {};

Account.createInstance = function () {
    var account = new Account();
    account.id = uuid.v4();
    Account.instances[account.id] = account;
    return account;
};
Run Code Online (Sandbox Code Playgroud)

但是因为我正在使用Object.defineProperty而不是prototype添加成员的属性,Account.instances并且Account.createInstance在调用时也会被实例化Object.create,因此是实例的属性.

在使用EcmaScript 5样式对象创建时,如何向类中添加静态成员?

Com*_*ine 5

对于 ES 5,如果你想要静态方法:

// A static method; this method only 
// exists on the class and doesn't exist 
// on child objects
Person.sayName = function() {
    alert("I am a Person object ;)");  
};

// An instance method; 
// All Person objects will have this method
Person.prototype.setName = function(nameIn) {
    this.name = nameIn;  
}
Run Code Online (Sandbox Code Playgroud)

见@ https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/


Ber*_*rgi 1

你不能。

我的类定义如下var Account = {};

这不是一个类(如果我们这样称呼经典模型),而只是一个原型对象。由于只有这个,您将需要对静态成员使用其他变量,例如实例缓存或创建函数:

var Account = {...};
var instances = [];
function createAccount(){...}
Run Code Online (Sandbox Code Playgroud)

当然,你可以命名它们:

var Account = {
    proto: {...},
    instances: [],
    instantiate: function create(){...}
};
Run Code Online (Sandbox Code Playgroud)

...但这看起来非常接近经典模式,不是吗?唯一的区别是您create在命名空间对象上有一个函数,而不是构造函数,如下所示命名空间对象。

您可能还对问题Object.create Prototype Chains感兴趣,我在其中讨论了像这样工作的完整继承模型,create以及inherit所有“类对象”从base.


进一步回答评论中的问题:

Object.create 不会使 EcmaScript 5 中的 new 运算符过时吗?

不。该new关键字做了两件事:设置新实例的原型链,并应用构造函数。Object.create只做第一件事,因此当您不需要函数(或不希望它执行)时可以使用它。

在你的例子中,你有这样的函数,所以经典模型在这里也不会出错。另请参阅使用“Object.create”而不是“new”