javascript中构造函数的静态方法模式

oso*_*ejo 7 javascript methods static design-patterns

function Foo(){...}
Foo.bar = function (){...};
Run Code Online (Sandbox Code Playgroud)

这是将静态方法添加到构造函数的唯一模式吗?特别是,是否无法在Foo()本身的定义中创建静态方法bar()?

Ate*_*ral 9

当你说"内部"时,听起来你需要一种干净的方式将所有东西放在一个地方.您可以使用支持静态声明的类继承库.或者只需拿一个并自己扩展即可添加该功能.

对于一个简单(但不那么紧凑)的方法来保持所有内容,你可以使用这样的东西:

var Foo = (function () {
    var ctor = function () {
        // the constructor
    };

    ctor.staticMethod = function () {
        // something static
    };

    return ctor;
})();
Run Code Online (Sandbox Code Playgroud)

但!真正重要的是使声明不言自明,它是静态的吗?您可以简单地将静态方法声明为原型方法,并通过一些代码注释传达它们是静态的(即不作用于实例)方法.没有任何合同执行如何调用这些方法,但几乎没有副作用.所以我会选择:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

用法:

// 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
Run Code Online (Sandbox Code Playgroud)

我发现上面的内容非常方便,特别是当你使用工厂设计模式时.您的类在其原型中可以有一些静态工厂方法,即使您只有一个您不知道其原始类的实例,也可以调用这些工厂方法.