function Foo(){...}
Foo.bar = function (){...};
这是将静态方法添加到构造函数的唯一模式吗?特别是,是否无法在 Foo() 本身的定义中创建静态方法 bar()?
最佳答案
当您说“内部”时,听起来您需要一种干净的方式将所有内容保存在一个地方。您可能会使用支持静态声明的类继承库。或者简单地采用一个并自己扩展它以添加该功能。
要以一种简单(但不是那么紧凑)的方式将所有内容放在一起,您可以采用如下方式:
var Foo = (function () {
var ctor = function () {
// the constructor
};
ctor.staticMethod = function () {
// something static
};
return ctor;
})();
但是!让声明不言自明地表明它是静态的到底有多重要?您可以简单地将您的静态方法声明为原型(prototype)方法,并通过一些代码注释传达它们是静态(即不作用于实例)方法的事实。不会有任何关于如何调用这些方法的契约(Contract)强制执行,但副作用很少。所以我会选择:
function Foo() {
// the constructor
// optionally define instance methods here
}
Foo.prototype = {
instanceMethod: function () {
// some instance method
// this.bar(); ...
},
staticMethod: function () {
// some static method
// return 2 + 3;
}
};
用法:
// Using "prototype" explicitly can be your contract for saying "this is static"
var sum = Foo.prototype.staticMethod();
var inst = new Foo();
var sum2 = inst.staticMethod(); // You have the added benefit of being able to call your static methods on instances
我发现上述内容非常有用,尤其是在您使用工厂设计模式时。您的类可以在其原型(prototype)中包含一些静态工厂方法,即使您只有一个您不知道其来源类的实例,您也可以调用这些工厂方法。
关于javascript - javascript中构造函数的静态方法模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9055828/