Ответ 1
Большинство из них можно сделать сами. Вызов голого конструктора без new
и получение строки является специальным для Date
по спецификации ECMA, но вы можете имитировать что-то подобное для этого.
Вот как вы это сделаете. Сначала объявите объект в шаблоне конструктора (например, функцию, которая предназначена для вызова с new
и которая возвращает ссылку this
:
var Thing = function() {
// Check whether the scope is global (browser). If not, we're probably (?) being
// called with "new". This is fragile, as we could be forcibly invoked with a
// scope that neither via call/apply. "Date" object is special per ECMA script,
// and this "dual" behavior is nonstandard now in JS.
if (this === window) {
return "Thing string";
}
// Add an instance method.
this.instanceMethod = function() {
alert("instance method called");
}
return this;
};
Новые экземпляры Thing могут иметь instanceMethod()
для вызова. Теперь просто добавьте "статическую" функцию в Thing:
Thing.staticMethod = function() {
alert("static method called");
};
Теперь вы можете сделать это:
var t = new Thing();
t.instanceMethod();
// or...
new Thing().instanceMethod();
// and also this other one..
Thing.staticMethod();
// or just call it plain for the string:
Thing();