JavaScript entry Basics of private variable _javascript tips

Source: Internet
Author: User
First look at the common function usage of javascript
Copy Code code as follows:

function sum (a,b) {
var C = 10;
function Add () {
C + +;
}
Add ();
Return a + B + C;
}
var d = sum (4,5);
Alert (d)//20

As you can see, external to interact with the sum of functions, only through the invocation and return value form, you cannot access the inside parameter C and internal function add (). This is normal logic for a function.
Next look at the class usage of JavaScript
Copy Code code as follows:

function sum (PA,PB) {
THIS.A = PA;
this.b = PB;
This.show = function () {
Alert (THIS.A + this.b);
}
}
var t = new sum (4,5);
T.show ();
alert (T.A);

Here, the object T of Sum is created by new. You can call method show through T to display parameters and, or you can take parameter information directly
The combination of two methods produces the effects of private variables and methods.

Copy Code code as follows:

function sum (PA,PB) {
var __c = 10; Private variable
function __ADDC () {//Private method
__c++;
}
THIS.A = PA; Public variables
this.b = PB; Public variables
this.setc = function (PC) {//Public method
__c = PC;
__ADDC ();
}
This.show = function () {//Public method
Alert (THIS.A + this.b + __c);
}
}
var t = new sum (4,5);
T.SETC (1);
T.show ();

As can be seen from this example, the variables and methods of VAR declaration cannot be invoked externally, but the external can interact with private variables through public method for the bridge.
Recommendation: For readability and distinction, private variables and methods add one or two underscores before naming.
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.