有什么理由在 TypeScript 中使用静态/私有静态方法?

and*_*dko 12 oop typescript

我正在考虑但找不到在 TypeScript 类中使用静态方法(尤其是私有静态)的任何理由。我在胡思乱想什么吗?我问这个问题是因为我看到了这样的代码:

class Abc {

  public someMethod() {
     Abc.myMethod();
  }

  private static myMethod() {
     ...
  }
} 
Run Code Online (Sandbox Code Playgroud)

PS对于那些试图向我解释静态和非静态方法之间的区别以及什么是私有方法的人。由于我多年的 C# 背景,我非常了解这些。如果您仔细阅读问题 - 这是关于在 TypeScript 中使用这些。

小智 12

我个人喜欢使用私有静态方法来表示纯函数。那么你绝对知道这样的方法永远不会改变对象的状态。

在面向对象编程范式中尽可能实现函数式编程会创建更多无副作用的代码,最终降低耦合。这导致代码不太容易出现对象状态错误、回归错误,并且通常更容易理解。

这是一个非常简单的例子:

interface DatabaseFoo {
    size: number;
    color: string;
}

class Foo {
    private static toDatabaseFoo(
        uid: string,
        color: number,
        length: number,
        width: number
    ): DatabaseFoo {
        let convertedData: DatabaseFoo;

        // Perform object specific data cleaning and/or transformations

        return convertedData;
    }

    private color: number;
    private length: number;
    private uid: string;
    private width: number;

    saveToPersistence(): void {
        const databaseFoo = Foo.toDatabaseFoo(
            this.uid,
            this.color,
            this.length,
            this.width
        );
        const jsonFoo = JSON.stringify(databaseFoo);

        // Save to persistence
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我非常同意你的说法“我个人喜欢使用私有静态方法来表示纯函数。”我自己也这样做,即使对于私有成员也是如此,以传达它是一个纯的、无副作用的函数。 (3认同)

Cod*_*nch 9

静态方法/属性和非静态方法/属性之间的主要区别在于:在内存级别,将为静态字段创建一部分内存,这些字段将在类中的所有对象之间共享。所以它适用于 C# 或 Java。

对于 javascript,此行为是在ES6+中实现的。但是对于早期版本的 Ecma Scripts,打字稿模拟了这种情况。

在您的情况下,方法myMethod()可以用作隐藏复杂的资源密集型功能的方法,该功能不与类的特定实例绑定,并且对最终用户隐藏。

看到这个代码:

class A {
    protected _p: string;
    constructor() { 
        this._p = "A";
    }
    public someMethod(value: string) {
        A.myMethod(this._p + value);
    }
    private static myMethod(p:string) {
        console.log(p);
    }
} 

class B extends A {
    constructor() { 
        super();
        this._p = "B";
    }
}

var a1 = new A();
a1.someMethod("_1");
var a2 = new A();
a2.someMethod("_2");
var b1 = new B();
b1.someMethod("_1");
Run Code Online (Sandbox Code Playgroud)


Mon*_* Ta 1

您将在您的类中使用私有方法。从外部无法访问它。与Java等相同。私有静态相同。

静态意味着您希望通过类名访问方法而不创建对象(实例化)。它也可以从外部类访问。如果没有静态,您需要创建一个对象。

class Abc {

  public someMethod() { 
     Abc.myMethod(); // Here you are able to access the static method myMethod because you are in the same class. It is not possible to access myMethod from another class directly. But someMethod() you can access directly which takes e.g. the data from myMethod();
  }

  private static myMethod() { // It is private and only accessible within the class and static therefore you can access it over the class name Abc.myMethod()
     ...
  }
} 
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助

  • 感谢您的回答,但这实际上并没有解释任何原因或可能的用例。 (5认同)