In the last section, the JavaScript object-oriented namespace describes how to define a JavaScript namespace. This section is followed by a concept-class. Although JavaScript does not have the class keyword, we must have this idea as developers. In C #, classes can be divided into instance classes and static classes, and JavaScript is also true.
I. Define the instance class: in the previous section, I defined a cnblogs. news namespace. Now I define a namespace named Article:
Copy codeThe Code is as follows:
Cnblogs. news. Article = function (){
Var _ this = this;
This. title = null;
This. content = null;
This. show = function (){
Document. write ("Document. write ("<p>" + _ this. content + "</p> ");
}
}
Create an object just like C:
Copy codeThe Code is as follows:
// Instantiate an object
Var article = new cnblogs. news. Article ();
// Assign values to attributes of an object
Article. title = "this is the title of the article ";
Article. content = "this is the content of the article ";
// Call the object Method
Article. show ();
2. Define static classes: the so-called static class is the member that calls the class directly. In other words, the class member belongs to the class and does not belong to the object. Take Article as an example. The Code is as follows:
Copy codeThe Code is as follows:
Cnblogs. news. Article = {
Title: "This is the title of the article ",
Content: "This is the content of the article ",
Show: function (){
Document. write ("Document. write ("<p>" + cnblogs. news. Article. content + "</p> ");
}
};
The call method is similar to that of C:
Cnblogs. news. Article. show ();
You may have discovered that the so-called JavaScript static class is actually a json object. Congratulations! Pai_^
3. How to choose:
So when to select an instance class and when to select a static class? in terms of personal experience (if I am not talking about it, please correct it. How can I always do it? ^), the development of some dom-dependent systems is relatively weak, highly reusable programs, such as tool classes, plug-in classes, structures, and static classes are required. If the program is highly dependent on dom, variables are often transmitted, or change the structure of the class. In this case, select the instance class. I personally admire the first solution, and its code style is more like C # than the second one. I think this will happen to my colleagues who are familiar with C #, ^_^.
Author: xiangshu