Object-oriented JavaScript (3): Private members and public members

Source: Internet
Author: User

In small projects for JavaScript use, just write a few function on the line. But in large projects, especially in the development of the pursuit of a good user experience of the site, such as SNS, will use a lot of javascrpt, sometimes JavaScript workload than C #, then write a bunch of function, it will appear very messy, disorganized, even a naming conflict, It's cumbersome to manage and maintain. In this case, we need to use object-oriented thinking to develop JavaScript. So let's just say:

This section refers to the private and public members of JavaScript, although JavaScript does not have the private and the publicly keywords, but it is the same sentence-as a developer we have an object-oriented mind!

Actually very simple, the nonsense to say less, read the following code and comments believe you will be at a glance!

Declaring a class is a method, in fact, in JavaScript, namespaces, classes, members .... All objects
MyClass =function () {
var _this=this;

Private variables
var aa= "11";

Exposing variables
this.bb= "22";

Private methods
function Fun1 () {
alert (AA);
alert (_THIS.BB);
}

Private methods
var fun2=function () {
alert (AA);
alert (_THIS.BB);
}

Public methods
This.fun3=function () {
alert (AA);
alert (_THIS.BB);
}
}

The test is as follows:
var mc=new MyClass ();
Mc.aa= "AA";//Error

mc.bb= "BB";//Correct

MC.FUN1 ();//Error

Mc.fun2 ();//Error

MC.FUN3 ();//correct

word : In the interior of the class

Variables or methods declared with the VAR keyword are private;

The method declared with the function keyword is private;

The variable or method declared with the This keyword is public.

All of this is for instance classes, and for static classes it is simpler, JavaScript static class is actually a JSON object, so all its members are public, are visible to the outside!

Object-oriented JavaScript (3): Private members and public members

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.