Appitizer ...
Статические методы в 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) способа добавления статических методов в класс.Приведенный ниже код получен из "Pro JavaScript с MooTools" от Mark Obcena.
Я включил еще немного информации, которой не хватало в ответе Джеймса Андино.Как свойство объекта
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);
};
2.Использование 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);
}
});
3.Добавление нового мутатора в Class.Mutators
// 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'