Douglas Crockford Classified the "class methods" in JavaScript into three types:
Private,
Privilegedand
Public.
Public MethodsThe obvious meaning:they can be accessed by the public.
Private Methods' Meaning is also clear:they cannot is accessed by the public.
So what is
Privileged Methods? To understand that, we should has a short review of what we implement public and private methods in JavaScript first.
Recall that, unlike languages like C + +, JavaScript does not has "class". Moreover, it does not has
Access SpecifiersLike
Public,
protectedand
Private. Lack of these features make the creation of private and public methods less clear than it should is.
To write a
Public MethodIn JavaScript, we do use the
. Prototypeproperty of the constructor function. For example:
function Footballplayer () {}; Declare a functionFootballPlayer.prototype.kick = function () {alert ("kick!");}; Create a public method kick in. Prototypevar Messi = new Footballplayer (); Messi.kick ();
From my previous article, you have learnt a
footballplayer.prototype is a object that is built Automatica Lly when the function is created. Object constructed with the Footballplayer, Messi, search through he
__proto__ chain When we tell him to kick. Obviously
Footballplayer.prototype is on the chain so Messi knows what to kick. All objects created by the
constructor function share the same
Footballplayer.prototype so they all can I Nvoke the public
method kick!
Private Methodsis kinda tricky. We declare private variable in a
ConstructorUsing the keyword
var:
Function Man () {var Wealth;var bath = function () {};function kiss () {}}
in this case, none of wealth, bath or kiss is accessible outsite the function man. Even man's public
methods
cannot access them.
However, the
Privileged Methodscan access the
Private MembersDue to the existence of
closures. They is very useful as they can act as a bridge between the Outsite world and the inner status of the object.
Consider the following example:
var func = function (A, b) { this.a = A; THIS.GETB = function () {return B}; A privileged method This.setb = function (n) {b=n;};//Another privileged method var B = b;}; func.prototype.getB2 = function () {return b*2}; Public Methodvar obj = new func; alert (Obj.getb ()); Privileged method can access private Balert (OBJ.GETB2 ()); Error:public method cannot access private BOBJ.SETB (one); alert (Obj.getb ());
So actually we can create
privileged methods easily by using the keyword
this!
Read MORE:
Prototype and Constructor in JavaScript by Redcapcoder
Private members in JavaScript by Douglas Crockford
A simple Example about privileged Methods in JavaScript