我想在 EcmaScript 5 JavaScript 中的类中添加一个静态函数。我的类定义如下所示:
var Account = {};
Object.defineProperty(Account, 'id', {
value : null
});
我会像这样创建一个新实例:
var theAccount = Object.create(Account);
theAccount.id = 123456;
现在我想向 Account
类添加一个静态函数。如果我使用构造函数和 prototype
属性创建了 Account
类,如下所示:
var Account = function () {
this.id = null;
};
...我可以这样做:
Account.instances = {};
Account.createInstance = function () {
var account = new Account();
account.id = uuid.v4();
Account.instances[account.id] = account;
return account;
};
但由于我使用 Object.defineProperty
而不是 prototype
属性来添加成员、Account.instances
和 Account。 createInstance
也会在调用 Object.create
时实例化,因此是实例的属性。
如何在使用 EcmaScript 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;
}
参见@https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/
关于javascript - 如何在 EcmaScript 5 中添加静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687038/