JavaScript's public, private, and privileged patterns _javascript tips

Source: Internet
Author: User
Summary
A private variable is declared within an object using the ' var ' keyword, and it can only be accessed by private functions and privileged methods.
Private functions are declared in the object's constructor (or by the Var functionname=function () {...} That can be called by a privileged function (including the object's constructor) and by a private function call.
The privileged method passes This.methodname=function () {...} To declare and possibly be called by code outside the object. It can use: this. Privileged function () to invoke a privileged function, using the private function () method to invoke the private function.
Public properties are defined by This.variablename and can be read and written outside the object. cannot be invoked by a private function.
Public Methods Pass Classname.prototype.methodname=function () {...} To define and can be invoked from outside the object.
The stereotype properties are defined by Classname.prototype.propertyname=somevalue.
Static properties are defined by Classname.propertyname=somevalue.
Also note the following: var function name =function () {...} This function is invoked with the attribute of a privileged function and a private function.
Cases:
Copy Code code as follows:

<title></title>
<script type= "Text/javascript" >
function Container (param) {
function Dec () {
if (Secret > 0) {
Secret-= 1;
Setsecret (7)
Alert (secret);
return true;
}
else {
Alert ("Over" +this.member);
return false;
}
}
This.dec = Dec;
This.dec = function Dec () {...} different from above code.
function Setsecret (num) {
Secret = num;
}
This.member = param;
var secret = 3;
var self = this;
This.service = function () {
if (Dec ()) {
alert ();
}
else {
return null;
}
}
}
// ---------------------------------------
function Start () {
Alert ("Start")
var test = new Container (' Liuqi ');
Test.setsecret (2);
Test.service ();
Test.service ();
Test.service ();
Test.service ();
var test2 = new Container (' Liuqi ');
Test2.service ();
Container.dec ();
}
</script>
<body>
<div onclick= "Start ()" style= "Color:blue" >click me</div>
</body>

JavaScript is the most misunderstood programming language in the world. Some people think it lacks the feature of information hiding because JavaScript objects cannot have methods of private variables.
But this is a misunderstanding. JavaScript objects can have private members.
Object
JavaScript is fundamentally about objects. An array is an object, and the method is an object, which is also an object. What is an object? Object is a collection of key-value pairs. The key is a string,
Values can be strings, numbers, Booleans, and objects (including arrays and methods). Objects are usually implemented as hashtable, so that values can be quickly fetched.
If the value is a function, I can call it a method. When the object's method is invoked, the "this" variable is assigned to the object. Method can access the instance through the "this" variable
Variable.
An object can be generated by the method-constructor of the initialization object. Constructors provide attributes that are provided by classes in other programming languages, including static variables and methods.
Public
The members of the object are public members. Any object can be accessed, modified, deleted, or added to a new member. There are two main ways to place members in a new object:
In the constructor
This technique is commonly used to initialize public instance variables. The "This" variable of the constructor is used to add members to the object.
Java code
Copy Code code as follows:

Functin Container (param) {
This.member = param;
}
Functin Container (param) {
This.member = param;
}

This way, if we construct a new object var MyContainer = Container (' abc '), then Mycontainer.member is ' abc '.
In the prototype.
This technique is commonly used to add public methods. When looking for a member and it is not in the object itself, it is found from the prototype member of the object's constructor.
The prototype mechanism is used to do inheritance. To add a method to all objects created by the constructor, simply add the prototype to the constructor:
Java code
Copy Code code as follows:

Container.prototype.stamp = function (string) {
return This.member + string;
}
Container.prototype.stamp = function (string) {
return This.member + string;
}

In this way, we can call the method Mycontainer.stamp (' Def '), and the result is ' abcdef '.
Private
Private members are generated by constructors. The normal var variable and the constructor parameters are called private members.
Java code
Copy Code code as follows:

function Container (param) {
This.member = param;
var secret = 3;
var that = this;
}
function Container (param) {
This.member = param;
var secret = 3;
var that = this;
}

The constructor creates 3 private instance variables: Param,secret and that. They are added to the object, but cannot be accessed externally, nor can they be the object's own
Public method Access. They can only be accessed by private methods. The private method is the internal method of a constructor.
Java code
Copy Code code as follows:

function Container (param) {
function Dec () {
if (Secret > 0) {
Secret-= 1;
return true;
} else {
return false;
}
}
This.member = param;
var secret = 3;
var that = this;
}
function Container (param) {
function Dec () {
if (Secret > 0) {
Secret-= 1;
return true;
} else {
return false;
}
}
This.member = param;
var secret = 3;
var that = this;
}

Private method Dec checks secret instance variables. If it is greater than 0, it decreases secret and returns true, otherwise it returns false. It can be used to limit this object to 3 times.
By convention, we define a private that variable. This is used to allow the private method to use this object. This is because there is an error in the ECMAScript language specification,
This error causes the internal method to be set incorrectly.
Private methods cannot be called by the public method. In order for the private method to be useful, we need to introduce the privileged method.
Privileged
The privileged method can access private variables and methods, and it itself can be accessed by public methods and outside. You can delete or replace the privileged method, but you cannot
Change it or force it to reveal its secrets.
The privileged method is allocated in the constructor using this.
Java code
Copy Code code as follows:

function Container (param) {
function Dec () {
if (Secret > 0) {
Secret-= 1;
return true;
} else {
return false;
}
}
This.member = param;
var secret = 3;
var that = this;
This.service = function () {
if (Dec ()) {
return that.member;
} else {
return null;
}
};
}
function Container (param) {
function Dec () {
if (Secret > 0) {
Secret-= 1;
return true;
} else {
return false;
}
}
This.member = param;
var secret = 3;
var that = this;
This.service = function () {
if (Dec ()) {
return that.member;
} else {
return null;
}
};
}

Service is the privileged method. The first three calls to Mycontainer.service () will return ' ABC '. After that, it returns NULL. The service invokes the private Dec method,
The Dec method accesses private secret variables. Service is visible to other objects and methods, but it does not allow direct access to private variables.
Closed Bag
Since JavaScript has closures, the public,private and privileged member models are feasible. This means that an internal method can always access its external method's
var variables and parameters, even after the external method returns. This is a very powerful feature of the JavaScript language. No JavaScript currently showing how to exploit this feature
Most of the programming books are not even mentioned.
Private and privileged members can only be generated when an object is constructed. Public members can be added at any time.
Mode
Public
Java code
Copy Code code as follows:

Function Constructor (...) {
This.membername = value;
}
Constructor.prototype.membername = value;
Function Constructor (...) {
This.membername = value;
}
Constructor.prototype.membername = value;

Private
Java code
Copy Code code as follows:

Function Constructor (...) {
var that = this;
var membername = value;
function MemberName (...) {...}
}
NOTE: function statements
function MemberName (...) {...}
is a shorthand for the following code
var membername = function membername (...) {...};
Function Constructor (...) {
var that = this;
var membername = value;
function MemberName (...) {...}
}
NOTE: function statements
function MemberName (...) {...}
is a shorthand for the following code
var membername = function membername (...) {...};

Privileged
Java code
Copy Code code as follows:

Function Constructor (...) {
This.membername = function (...) {...};
}
Function Constructor (...) {
This.membername = function (...) {...};
}

Translator Note: I think it's easy to simply view the privileged method as a public method in a constructor because the privileged method can be accessed by the outside and public methods,
And it can access the private variable itself.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.