【问题标题】:How to call a method of a class without instantiating it?如何在不实例化的情况下调用类的方法?
【发布时间】:2019-01-13 00:05:42
【问题描述】:

我创建了一个 Tools 类来扩展其中的每个类,因为它包含所有类都使用的一组函数。

我像这样导出我的课程:

工具.ts

export abstract class Tools {
  getRandom(bytes) {
    return 21 // Example
  }
}

Main.ts

import * as Tools from './Tools.ts'

class Main extends Tools { // <-- I get the error from the Tools keyword here
  constructor() {
    super() // If not, I get an error
  }

  token() { // Example method
    this.getRandom(2)
  }
}

我得到的错误:

Type 'typeof import("[...]/tools")' is not a constructor function type

我不想在每个类中都使用new Tools(),我想直接调用该类的函数。

如何在不实例化其他类的情况下导入一个类并调用它的方法?

【问题讨论】:

    标签: typescript import export


    【解决方案1】:

    虽然您的问题之前已解决,但我想插话,因为我认为您想要实现与扩展类在语义上不同的东西。将实用程序函数存储在 Tools 类中并对其进行扩展会阻止您进一步继承。此外,您可能只想使用一个实用程序函数,但仍然继承所有这些函数,这在 lodash 的情况下会很糟糕。

    您最有可能寻找的是所谓的静态方法。无需特定类实例即可直接调用的类方法。

    // In Tools.ts
    export class Tools {
        // https://xkcd.com/221/
        public static getRandomNumber() {
            return 4; // chosen by fair dice roll.
                      // guaranteed to be random. 
        }
    }
    
    // Somewhere else
    import { Tools } from "./Tools";
    
    export class Main {
        public doSomething() {
            const randomNumber = Tools.getRandomNumber();
        }
    }
    

    但是,在 TypeScript 中,通常不鼓励导出仅包含静态方法的类,这些方法应封装在它们自己的函数中,您可以显式导入这些函数以减少包大小:

    // In Tools.ts
    export function getRandomNumber() {
        // https://xkcd.com/221/
        return 4; // chosen by fair dice roll.
                  // guaranteed to be random. 
    }
    
    // Somewhere else
    import { getRandomNumber } from "./Tools";
    
    export class Main {
        public doSomething() {
            const randomNumber = getRandomNumber();
        }
    }
    

    【讨论】:

    • 哦该死的儿子!谢谢!事实上,这正是我一直在寻找的。另外,你可能会觉得这个也很有趣:dilbert.com/strip/2001-10-25(这是我的灵感)你让我开心。
    • 静态的用法和告诉推荐的使用导出函数的方法值得???
    【解决方案2】:

    您正在使用命名的导出,因此您的导入语句应如下所示:

    import { Tools } from './Tools.ts'
    

    如果您不喜欢显式调用super,可以跳过constructor。在这种情况下,JavaScript 运行时会为您调用它。

    class Main extends Tools {
      token() {
        this.getRandom(2)
      }
    }
    

    【讨论】:

    • 解决了!感谢您的帮助!没想到!
    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 2020-12-19
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2014-06-18
    相关资源
    最近更新 更多