简体   繁体   English

Crockford解释私人财产

[英]Crockford explanation of private properties

I read this: private Javascript variables from Crockford site 我读到了这个:来自Crockford网站的私有Javascript变量

but I have some perplexity on his terminology: 但我对他的术语有些困惑:

here he says: 在这里他说:

The members of an object are all public members Ex. 对象的成员都是公共成员Ex。 `this.membername = value; `this.membername = value;

after: 后:

Private variables are not accessible to the outside, nor are they accessible to the object's own public methods. 私有变量不能被外部访问,也不能被对象自己的公共方法访问。

and then: 接着:

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside 特权方法能够访问私有变量和方法,并且本身可以访问公共方法和外部

So it seems as privileged methods are different from public methods but if I do: 因此,特权方法似乎与公共方法不同,但如果我这样做:

function S()
{
   var a = 11; // PRIVATE
   this.get = function() { return a; }; // PUBLIC AND PRIVILEGED???
}

new S().get();

there get method is a public method and also a privileged method... so when he says the public methods can't access private member what is he concerning? get方法是一种公共方法,也是一种特权方法...所以当他说公共方法无法访问私人成员时他会关注什么?

Thanks. 谢谢。

The only way that get is able to access a is through closure, so that effectively makes it a privileged method. 唯一的方法get能够访问a就是通过关闭,以便有效地使它成为一个特权方法。 Whether it is public or not has nothing to do with the fact that it is privileged. 它是否公开与它特权的事实无关。

To answer specifically your question about public methods, since you seem to understand the idea of privilaged, consider from your example: 要专门回答关于公共方法的问题,因为您似乎理解了特权的想法,请从您的示例中考虑:

S.prototype.something = function ...

This would be public but not privilaged since it can't access the private variable a 这将是公开的,但不是特权,因为它无法访问私有变量a

That you can get the value of a which is a private member of S doesn't mean that you could "access" a . 你可以得到a S的私人成员的价值并不意味着你可以“访问” a For example, you can't change the value of a unless a method, like set , is provided to do that. 例如,你不能改变的值a ,除非一个方法,像set ,提供这样做。 You are given a method (an interface, if you may) get which is "previleged" to get the value of a which is a private member of S. 给你一个方法(一个接口,如果你可以) get ,这是“previleged”得到的值a是S的私有成员

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

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