JavaScript writing: The writing of JavaScript classes

Source: Internet
Author: User
Tags object variables return static class access

A function in JavaScript is a class that uses this to set the public member variables and methods of a class, such as:
function MyClass (name) {
var str = "private string"; Private field
function Privatefn () {//private method alert (str);
};
THIS.name = name;
THIS.PUBFN = function () {
Privatefn (); Call Private method
Alert ("MYCLASS.PUBFN");
}
}
Create an object with new when used:
var obj = new MyClass ("123");
var name = Obj.name; Access public field
OBJ.PUBFN (); Call public method
The above is the most common type of JavaScript, the actual application is less, the most used is written in the form of static class, JavaScript static class has two ways:
1. Writing like a JSON object
var MyClass = {
Name: "123",
Pubfn:function () {
Alert ("Pubfn1 is called");
}
};

Call form: Myclass.name, MYCLASS.PUBFN ()
This style of writing makes the members of the class have access to public.
2. The writing of anonymous function
var myclass = function () {
var name = "123"; Private field
var privatefn = function () {//private method
alert (name);
}
return{//return public field and method
Name: "Hello" + Name,//public field
Pubfn:function () {
Privatefn (); Call Private method
Alert ("This is a returned function"); Public method
}
}
}();
The advantage of this approach is that private and shared member methods and variables can be separated, and the actual application can be written in a complex logical private method, while return a common interface calls the private method.
Call form: MyClass. Name, MYCLASS.PUBFN ()
Note the parentheses at the end of the class, which is the function of creating objects, removing parentheses, and calling the form: MyClass (). Name, MyClass (). PUBFN ().
This article links http://www.cxybl.com/html/wyzz/JavaScript_Ajax/20120608/28906.html

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.