简体   繁体   中英

Crockford explanation of private properties

I read this: private Javascript variables from Crockford site

but I have some perplexity on his terminology:

here he says:

The members of an object are all public members Ex. `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?

Thanks.

The only way that get is able to access a is through closure, so that effectively makes it a privileged method. 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

That you can get the value of a which is a private member of S doesn't mean that you could "access" a . For example, you can't change the value of a unless a method, like set , is provided to do that. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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