问题描述
是否存在模仿受保护对象属性的JavaScript模式,就像您在C ++等语言中看到的那样?
Is there a JavaScript pattern which mimics "Protected" object properties like what you see in languages like C++ ??
基本上,我想创建一个Object A具有许多受保护对象属性,只能从对象A的原型中定义的方法访问。即 - 不能从A的非原型方法公开访问。
Basically, I'd like to create an Object A which has a number of "protected" object properties which can be accessed ONLY from methods which are defined from the prototype of Object A. i.e. - NOT accessible publicly from non-prototyped methods of A.
例如,理想情况是这样的:
For instance, ideally would be like so:
function A(){
var prop1 = 1;
}
A.prototype.myFunc = function(){
var newVar = this.prop1; //newVar now is equivalent to 1
}
var instanceOfA = new A();
var newVar2 = instanceOfA.prop1; //error given as prop1 is "protected"; hence undefined in this case
BTW - 我不希望特权成员函数的模式访问私有属性成员函数仍然是公共的。
BTW - I do not want the pattern of privileged member functions accessing private properties since the member function is still public.
推荐答案
没有对象属性只能从<$ c $的原型方法中访问c> A 而不是来自 A
的非原型方法。该语言没有这种类型的功能,我不知道任何解决方法/黑客实现它。
There is no object property that can only be accessed from prototyped methods of A
and not from non-prototyped methods of A
. The language doesn't have that type of feature and I'm not aware of any work-around/hack to implement it.
使用,您可以创建成员属性只能从预定义的非原型方法(在构造函数中定义的方法)访问。因此,如果您尝试仅限制对一组预定义方法的访问,则可以实现此目的。除此之外,我认为你运气不好。
Using Doug Crockford's methods, you can create member properties that can only be accessed from predefined non-prototyped methods (those defined in the constructor). So, if you're trying to limit access only to a predefined set of methods, this will accomplish that. Other than that, I think you're out of luck.
如果你想要其他想法,如果你描述的更多是关于你的想法,你可能会得到更多的帮助实际上试图在你的代码中完成,而不仅仅是如何用另一种语言模拟一个功能。 Javascript与C ++有很大的不同,最好从问题的需要开始,而不是试图找到一些C ++特性的类比。
If you want other ideas, you'd probably get more help if you describe more about what you're actually trying to accomplish in your code rather than just how to emulate a feature in another language. Javascript is so much different than C++ that it's better to start from the needs of the problem rather than try to find an analogy to some C++ feature.
这篇关于如何在JavaScript中创建受保护的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!