如何从打字稿中的静态方法获取价值?

How to get value from static method in typescript?

在我的打字稿中,static中添加了一个方法。后来我想打电话给同样的。但是出现错误......在编译代码时。我的代码有什么问题吗?谁能帮助我理解 typescript 中的 static 属性?

这是我的代码:

class Car { 
    private distanceRun: number = 0;
    color: string;

    constructor(public hybrid:boolean, color:string="red") {
        this.color = color;
    }

    getGasConsumption():string { 
        return this.hybrid ? "Low" : "High";
    }

    drive(distance:number) {
        return this.distanceRun += distance;
    }

    static horn():string {
        return "HOOONK!";
    }

    get distance():number {
        return this.distanceRun;
    }

}

let newCar = new Car(false);
console.log(newCar.color);
console.log(newCar.horn()); //shows error as Property 'horn' does not exist on type 'Car'..

Live

静态成员不附加到 class 的实例。它们附加到 class 本身。

您需要通过 class 调用静态方法和属性,而不是实例 - 像这样Car.horn()

Live example

你可以看到,那个

class Test {
   get() { 

   }

   static getStatic() {

   }
}

编译成这个

function Test() {

}

Test.prototype.get = function () {

};

Test.getStatic = function () {

};

由此可见,getStaticTest本身中,而getTest的原型中,将被引用对象,通过 Test function-constructor.

创建