javascriptangularjsinheritanceprototypal-inheritanceangularjs-provider

How to prevent direct access to properties when inheriting from a base provider?


This is a follow up to How to inherit from base provider (not the provider factory)?. The proposed solution suggests a combination of angular.extend and angular.copy (which can be done with just angular.merge on Angular 1.4) to copy the base provider implementation into all other providers.

But this led to another issue that I was not expecting. With this technique, my providers are now configurable through the provider.setX function, along with direct access to provider.config.x property.

Here's an example demonstrating the issue:


Solution

  • Not really sure what you're after, but this.config.x isn't a variable but a property, and that's why it's accessible.

    If you want it to be inaccessible, you need to declare it as a local variable var config = {} inside the scope of the controller/service/factory/wherever you're setting it. Because local variables inside a function/method are inaccessible outside their scope, unless they're closures.

    Here's a version of your code that instantiates a function BaseClient (no longer a provider though, just a regular function) which contains a local variable that can not be touched. Again, I don't know if this is what you're after since I don't know which problem you're trying to solve.

    http://codepen.io/anon/pen/ZGazqo?editors=101