【问题标题】:cache within getters/setters?在 getter/setter 中缓存?
【发布时间】:2015-08-25 06:01:20
【问题描述】:

如果我有这样的吸气剂:

export class foo{
    aaa: number;
    bbb: number;
    ccc: number;

    constructor(){
        //whatever
    }

    get getHeight(f: number){
        return (f + 16) * Math.ceil(Math.round(Math.tan(aaa) + bbb/2) * ccc);
    }
}

其中aaabbbccc 是在运行时不会更改的常量。

我必须在运行时从其他类多次调用 getter,所以我希望能够通过“缓存”Math.ceil(Math.round(Math.tan(aaa) + bbb/2) * ccc) 尽可能降低性能。是否可以这样做而不必在 foo 类中创建一个全新的变量?

*额外问题:打字稿中是否可以将相同的变量类型合并为一个?就像在 java 中一样,我可以这样做:

int aaa, bbb, ccc;

但似乎打字稿不允许这样做。

【问题讨论】:

    标签: caching typescript


    【解决方案1】:

    是否可以做到这一点而不必在 foo 类中创建一个全新的变量

    不。 TypeScript 没有 静态函数局部变量,这实际上是您所要求的。

    打字稿中是否可以将相同的变量类型合并为一个?就像在java中一样,我可以做类似的事情

    不是 TypeScript 中标准方式的一部分 + 我在这里没有聪明的技巧。

    【讨论】:

      【解决方案2】:

      听起来您应该将此计算导出到一个外部静态类,该类在类定义上执行一次此计算,如下所示:

      class Calculator {
          static a : number = 5;
          static b : number = 6;
          static c : number = 7;
          static height : number = Math.ceil(Math.round(Math.tan(Calculator.a) + Calculator.b/2) * Calculator.c);
      }
      
      export class foo{
      
          constructor(){
              //whatever
          }
      
          getHeight(f: number){
              return (f + 16) * Calculator.height;
          }
      }
      

      【讨论】:

        【解决方案3】:

        我不确定你想做什么。但那是怎么回事? Playground

        export class foo{
            /* Is not visible outside of foo. */
            private static factor = Math.ceil(Math.round(Math.tan(foo.aaa) + foo.bbb/2) * foo.ccc);
        
            public constructor(){
                //whatever
            }
        
            public getHeight(f: number){
                return (f + 16) * foo.factor;
            }
        }
        
        export module foo {
            /* Use module mixing for constant variables, */
            export const aaa = 1;
            export const bbb = 2;
            export const ccc = 3;
        }
        

        还是这样? Playground

        export class foo{
        
            /* or readonly propierties. */
            public get aaa(){ return 1;};
            public get bbb(){ return 2;};
            public get ccc(){ return 3;};
        
            /* Is still not visible outside of foo. */
            private static factor = Math.ceil(Math.round(Math.tan(foo.aaa) + foo.bbb/2) * foo.ccc);
        
            public constructor(){
                //whatever
            }
        
            public getHeight(f: number){
                return (f + 16) * foo2.factor;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2023-03-07
          • 1970-01-01
          • 2014-09-13
          • 1970-01-01
          • 1970-01-01
          • 2011-06-13
          • 2010-11-13
          • 2021-10-17
          • 2016-02-24
          相关资源
          最近更新 更多