How to declare local function inside ES6 class?

前端 未结 2 2018
后悔当初
后悔当初 2021-01-02 12:26

I have a function that can be used only inside a class and don\'t want it to be accessible outside the class.

class Auth {
  /*@ngInject*/
  constructor($htt         


        
相关标签:
2条回答
  • 2021-01-02 12:32

    You could use a Symbol:

    const localFunc = Symbol();
    class Auth {
      /*@ngInject*/
      constructor($http, $cookies, $q, User) {
        this.$http = $http;
        this.$cookies = $cookies;
        this.$q = $q;
        this.User = User;
    
        this[localFunc] = function() {
          // I am private
        };
      }
    }
    
    0 讨论(0)
  • 2021-01-02 12:48

    No, there is no way to declare local functions in a class. You can of course declare (static) helper methods and mark them as "private" using underscore prefixes, but that's probably not what you want. And you can always declare the local function inside of a method.

    But if you need it multiple times then the only way to go is to place it next to the class. If you are writing a script, an IEFE will be necessary as usual. If you're writing an ES6 module (which is the preferred solution), privacy is trivial: just don't export the function.

    0 讨论(0)
提交回复
热议问题