2

I'm trying out making my own Javascript library and want to think it through.

I stumbled upon a convention to create private functions inside a class by prefixing it with underscore _, but there's still access to them. It looks like this:

export default class Test {
  constructor() {
    this._privateFunction();
  }
  _privateFunction() {
    ...
  }
}

I'm thinking about putting functions outside of exported class. Is this a good idea?

export default class Test {
  constructor() {
    privateFunction();
  }
}

function privateFunction() {
  ...
}

I could not find a way to access the function, when declared outside of exported class, so it seems like a viable alternative.

Is it a good idea? Wouldn't it create problems with parsing in the browser?

fraunos
  • 23
  • 3
  • 1
    Related (not a duplicate): https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes – k0pernikus Jul 25 '19 at 08:46
  • Defining the private function such that it can't possibly be accessed outside makes great sense IMO. Properties that start with underscores can still be accessed, but if you want the property to actually be private, the underscore strategy isn't a good one. Only real issue is that only some browsers support ES6 modules - I'd use Webpack or something to bundle the code first. – CertainPerformance Jul 25 '19 at 08:48
  • Does the private function need to access other things within the class at all? If so, you'll have to jump through `bind` or `call` hoops every time you call it. – James Thorpe Jul 25 '19 at 08:50
  • @JamesThorpe I guess I just wouldn't change the state without passing the data to the function. I'd return a value and then save it in the class somehow. – fraunos Jul 25 '19 at 08:59
  • Are you calling the function from multiple methods of the class? – Bergi Jul 25 '19 at 09:09

1 Answers1

2

Yes, using closures to keep things (including functions) private is a totally normal and common approach. There is not problem with parsing.

A disadvantage of this approach is that the private function is just a function, not a method. That means you need to explicitly pass the instance as an argument to have it available in there:

export default class Test {
  constructor() {
    privateFunction(this);
  }
}

function privateFunction(self) {
  …
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375