8

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($http, $cookies, $q, User) {
    this.$http = $http;
    this.$cookies = $cookies;
    this.$q = $q;
    this.User = User;

    localFunc(); // Need to create this function, and need it to be accessible only inside this class
  }
}

What I have done so far is declaring the function outside the class

function localFunc() {
  return 'foo';
}
class Auth {
  ...
}

However, this's not good as it pollutes the global function, except I wrapped it inside IIFE. So, is there somehow I can create a local function inside a ES6 class?

lvarayut
  • 13,963
  • 17
  • 63
  • 87
  • 3
    If you are using an ES6 module loader, declaring the function outside of the class won't pollute global scope. It's the way to go to ensure private functions in ES6 – CodingIntrigue Nov 17 '15 at 15:11
  • 1
    @MichałPerłakowski I don't think it's a duplicate, the [suggested canonical](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes) deals with *stateful, instance-specific properties* not functions/methods. – Bergi Jun 01 '17 at 02:46

2 Answers2

13

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • If you place the function next to the class, it won't have access to `this`, so you'll have to pass it as a parameter. – Dan Dascalescu Jun 01 '17 at 02:25
  • @DanDascalescu Sure, I think the OP did deliberately ask for a *function* though not a *method*. – Bergi Jun 01 '17 at 02:44
0

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
    };
  }
}
Lee
  • 2,993
  • 3
  • 21
  • 27