只使用常量的静态javascript函数会被编译为常量吗

Will static javascript function using only constants be compiled to constant

本文关键字:常量 编译 函数 javascript 静态      更新时间:2023-09-26

将使用以下javascript

var StaticTest_A = (function () {
  function StaticTest_A() {
  }
  StaticTest_A.GetConstant = function () {
    return StaticTest_B.MyNumber + StaticTest_B.MyNumber;
  };
  return StaticTest_A;
})();
var StaticTest_B = (function () {
  function StaticTest_B() {
}
StaticTest_B.MyNumber = 5;
  return StaticTest_B;
})();

从该TypeScript 生成

class StaticTest_A
{
   static GetConstant():number
   {
       return StaticTest_B.MyNumber + StaticTest_B.MyNumber;
   }
}
class StaticTest_B
{
   static MyNumber = 5;
}

StaticTest_A.GetConstant()返回一个常量,还是每次调用都会计算该函数?

不,该表达式每次都会运行,它应该运行,因为正如Pointy所指出的,StaticTests_B.MyNumber可能在此期间发生变化。此外,TypeScript不会更改您编写的代码以提高性能——这实际上不是编译器的目标。

如果出于性能原因,您只希望计算一次,那么您必须想出自己的解决方案。例如,您可以创建一个可重用的decorator,它在第一次运行时缓存值,然后返回缓存的值。然后你可以在任何你喜欢的地方使用这个装饰器:

function methodMemoize(target: Function | Object, key: string, descriptor: TypedPropertyDescriptor<() => any>) {
    const originalValue = descriptor.value;
    let hasRun = false;
    let returnedValue: any;
    descriptor.value = function(...args: any[]) {
        if (!hasRun) {
            returnedValue = originalValue.apply(this, args);
            hasRun = true;
        }
        return returnedValue;
    };
}
class StaticTest_A
{
    @methodMemoize
    static GetConstant()
    {
        console.log("run only once");
        return StaticTest_B.MyNumber + StaticTest_B.MyNumber;
    }
}
class StaticTest_B
{
   static MyNumber = 5;
}
StaticTest_A.GetConstant(); // "run only once", returns 10
StaticTest_A.GetConstant(); // returns cached 10