简体   繁体   English

从基本提供程序继承时如何防止直接访问属性?

[英]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.提议的解决方案建议结合使用angular.extendangular.copy (可以在 Angular 1.4 上仅使用angular.merge来完成)将基本提供者实现复制到所有其他提供者中。

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.使用这种技术,我的提供者现在可以通过provider.setX函数以及对provider.config.x属性的直接访问进行配置。

Here's an example demonstrating the issue:这是一个演示该问题的示例:

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.不太确定你想要什么,但是this.config.x不是变量而是属性,这就是它可以访问的原因。

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.如果您希望它无法访问,则需要在控制器/服务/工厂/无论您在哪里设置它的范围内将其声明为局部变量var config = {} 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.这是您的代码的一个版本,它实例化一个函数BaseClient (虽然不再是提供者,只是一个常规函数),其中包含一个无法触及的局部变量。 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 http://codepen.io/anon/pen/ZGazqo?editors=101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM