Private variables for getting started with javascript

Source: Internet
Author: User

First, let's look at the common functions of javascript.
Copy codeThe Code is 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

It can be seen that the external interface must interact with the function sum. It can only be called and returned, but cannot access the parameters c and internal functions add (). This is a normal logic for functions.
Next, let's look at the class usage of javascript.
Copy codeThe Code is 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. );

Here, the sum object t is created through new. Using t, you can call the show method to display the parameters and, or directly retrieve the parameter information.
Use both methods to generate private variables and methods.

Copy codeThe Code is as follows:
Function sum (pa, pb ){
Var _ c = 10; // Private variable
Function _ addc () {// Private Method
_ C ++;
}
This. a = pa; // public variable
This. B = pb; // public variable
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 ();

From this example, we can see that variables and Methods declared by var cannot be called externally, but external variables can interact with private variables through public methods as a bridge.
Suggestion: To facilitate reading and differentiation, add one or two underscores before the private variables and methods.

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.