简体   繁体   English

在 javascript class 上使用 static 方法

[英]using static method on javascript class

I am concerned about which one is more faster.我担心哪个更快。 Should I use create a new object from a class and use that object or use class with static methods. Should I use create a new object from a class and use that object or use class with static methods.

export default class AuthServices { 
    static async login (data) {}
    static async register (data) {}
}

The above code used static method and I can access login and register function by calling class name first.上面的代码使用了 static 方法,我可以通过首先调用 class 名称访问loginregister function。 Should I get rid of static and create an object on the file that is going to call these functions.我是否应该摆脱 static 并在要调用这些函数的文件上创建一个 object 。

You can simply use an object literal for AuthServics instead of a class.您可以简单地将 object 文字用于 AuthServics,而不是 class。

export default const AuthServices =  { 
      login: async (data) {}
      register: async (data) {}
}

If you want to use class then use static methods and do not instantiate from class.如果你想使用 class 然后使用 static 方法并且不要从 class 实例化。 Access the methods like this访问这样的方法

AuthServices.login()

There is no need to create multiple copies of these methods in memory.无需在 memory 中创建这些方法的多个副本。

I think it would be better to implement AuthService as a singleton with a static method to get the instance.我认为最好将AuthService实现为 singleton 和 static 方法来获取实例。 (Since you would want to have a global access to this service) (因为您希望全局访问此服务)

class AuthService {

  constructor() {
    if (!AuthService._instance) {
      AuthService._instance = this;
    }
    return AuthService._instance;
  }

  static getInstance() {
    return this._instance;
  }

  async login(data) {
   //Implementation
  }

  async register(data) {
  //Implementation
  }
}

To access it you would do something like this:要访问它,您将执行以下操作:

const authService = AuthService.getInstance();

authService.register();
authService.login();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM