1

Looking at other threads on stack overflow, it looks complicated to have private methods/variables within an ES6 Class.

I'm using Angular 1.5 but Controllers in Angular 2 are written using Classes. We wanted to make our code ready for a future migration.

This cause a problem: all the methods and variables within that Class are now available in the view, so you can from the view (the HTML), invoke MyController.privateMethod(); which is an issue.

How do we deal with that? I would prefer to use an ES6 module but I'm not sure it's recommended for an Angular 2 Controllers migration.

Here is a code example:

class MyController {

  constructor(){
    this.foo = 'foo';
  }

  privateMethod() {
    ...
  }

  publicMethod(){
    ...
  }

}

angular.module('myApp').controller('MyController', MyController);

Thanks!

Community
  • 1
  • 1
  • use the $scope and don't define your private functions as part of that scope. That way they won't be callable from the view. – yBrodsky Dec 20 '16 at 17:38
  • The `class` syntax actually just creates a function and adds functions to the `prototype`. Don't let the [class syntax trick you](https://github.com/joshburgess/not-awesome-es6-classes) into forgetting how to write good JS. The module pattern should work well. – 4castle Dec 20 '16 at 17:55

1 Answers1

2

The ES6 class is really just some syntactic sugar of the es5' old prototypal pattern. There is no explicit way to declare methods inside as public/private/protected.

So if you really want it to be private, you can declare outside of the class and export the class only. ES6 modules are not in the global namespace. Anything that you declare in your module but do not export will not be available to any other part of your program, but will still be available to your module during run time. This way, you have private properties and methods.

privateMethod() {
  ...
}

class MyController {

  constructor(){
    this.foo = 'foo';
  }

  publicMethod(){
    ...
  }

}
export default MyController;

However, to be frank, even though angular2 claims to be able to written in ES6/ES5, but you lose a lot comparing to using Typescript which the framework is written and claims to be a superset of JS but still some differences. Just my 2 cents. :-)

LeOn - Han Li
  • 9,388
  • 1
  • 65
  • 59