1

I'm currently using ALTJS on my javascript project and so am pretty much stuck with ES6 classes.

My questions is in regards to said classes. Is there a way to have private internal methods? For example:

class something() {
  constructor(){}
  methodOne(){}
  methodTwo(){}
}

You cannot access method two from inside method one and vice verser. In that case, what is the correct way to have a internal utility function. For example, some code that completes a calculation, that multiple methods should use, that I wouldn't want to repeat multiple times (DRY).

I understand that there are static methods. However, it seems bizarre that I then have to access these by calling something.staticMethod. In this case there is no need for the method to be public.

I've read a lot of es6 class articles online and none of them seem to address this concern.

Thanks!

pezza3434
  • 195
  • 3
  • 10

2 Answers2

3

JavaScript objects are always "fully exposed". If you have access to an object, you can completely traverse it, and there's (currently) no way to limit that.

What can be done is hide away "private" or "internal" functionality or data using several methods:

  1. If using a module system, only export the public part:

    function priv() {
      //do something
    }
    
    export class TheClass {
      myMethod() { priv(); }
    }
    
  2. You can wrap your code in an IIFE:

    const TheClass = (function() {
      function priv() {
        //do something
      }
    
      return class TheClass {
        myMethod() { priv(); }
      }
    })();
    
Amit
  • 45,440
  • 9
  • 78
  • 110
1

Yea, you just put the "internal" methods outside of what is being exported.

function privateMethod() {
  //Do some private stuff.
}

export default somefunction() {
  //Do some stuff
  privateMethod();
}

or if you wanted to have your helper methods in a separate file and import them when you need them, you could do it this way:

import { methodOne, methodTwo } from "./helpers.js";

export default somefunction() {
  //Do some stuff
  methodOne();
}
Pytth
  • 4,008
  • 24
  • 29
  • What does this have to do with ES6 classes? – Ajedi32 Nov 18 '15 at 22:24
  • 1
    My apologies. The premise is still the same, however. I guess my answer would work if you build classes the way most people do by giving them their own file and going from there. That way, the only publicly available methods are those that you export from the file your class file was defined in. – Pytth Nov 18 '15 at 22:28