是否有最佳实践或通用解决方案来为MooTools生成的类添加对“静态”方法和变量的支持?
特别是,有没有什么方法可以确保在调用实例initialize
方法之前进行静态初始化?
注意:从未使用过MooTools。不过,我使用了Prototype,它具有相似的Class
系统(MooTools是“灵感来自”还是Prototype的分支,具体取决于您问的是谁)。
只需将它们作为属性添加到结果“类”:
var MyClass = new Class(properties);
MyClass.staticMethod = function() {
// ...
};
((以上第一行来自the docs;其余为我的加法。)
您知道在任何新实例上都会在initialize
之前发生,因为您没有在附加静态方法(或属性)之前就没有创建新实例的机会。
我知道这篇文章很旧,但是我想给出一个比已经说的更好的答案。我建议静态方法使用以下语法:
var MyClass = new Class({
initialize: function() {
this.method();
MyClass.staticMethod();
}
,
method: function() {}
}).extend({
staticMethod: function() {}
});
.extend({})
方法是在类上添加静态方法的标准方法。
我唯一不喜欢的是MyClass.staticMethod();
语法,但是没有很多更好的选择。
JavaScript中的静态方法是引用它们的Object的属性。它们没有添加到对象的原型中。
有两种向JavaScript中的对象添加函数的方法。下面,我向虚构的对象“ MyObject
”添加方法。
属性
MyObject.staticMethod = new function() {};
MyObject.staticMethod(); // Call static method.
方法
MyObject.prototype.instanceMethod = new function() {};
new MyObject().instanceMethod(); // Call instance method.
有三(3)种向类添加静态方法的方法。下面的代码来自Mark Obcena的“ Pro JavaScript with MooTools”。
[我提供了Arcabard的答案中缺少的更多信息。
var Person = new Class({
// Instance Variables
name: '',
age: 0,
// Constructor
initialize: function(name, age) {
this.name = name;
this.age = age;
},
// Instance Methods
log: function() {
console.log(this.name + ', ' + this.age);
}
});
// Static Property
Person.count: 0;
// Static Methods
Person.addPerson: function() {
this.count += 1;
};
Person.getCount: function() {
console.log('Person count : ' + this.count);
};
extend()
var Person = new Class({
// Instance Variables
name: '',
age: 0,
// Constructor
initialize: function(name, age) {
this.name = name;
this.age = age;
},
// Instance Methods
log: function() {
console.log(this.name + ', ' + this.age);
}
});
Person.extend({
// Static Property
count: 0,
// Static Methods
addPerson: function() {
this.count += 1;
},
getCount: function() {
console.log('Person count : ' + this.count);
}
});
Class.Mutators
]中添加一个新的mutator// This will create a shortcut for `extend()`.
Class.Mutators.Static = function(members) {
this.extend(members);
};
var Person = new Class({
Static: {
// Static Property
count: 0,
// Static Method
addPerson: function() {
this.count += 1;
},
getCount: function() {
console.log('Person count : ' + this.count);
}
},
// Instance Variables
name: '',
age: 0,
// Constructor
initialize: function(name, age) {
this.name = name;
this.age = age;
},
// Instance Methods
log: function() {
console.log(this.name + ', ' + this.age);
}
});
使用静态方法的示例。
// Creating a new Person instance
var mark = new Person('Mark', 23);
mark.log();
// Accessing the static method
Person.addPerson();
Person.getCount() // 'Person count: 1'
摘录自“带有Mootools的Pro Javascript”