In the previous section of the JavaScript object-oriented namespace, you said how to define a JavaScript namespace, which is followed by a concept-class. Although there is no class keyword in JavaScript, we must have this idea as a developer. Classes can be divided into instance classes and static classes in C #, as are JavaScript.
First, define the instance class: In the previous section I defined a Cnblogs.news namespace, now define a class named article in this namespace:
Copy Code code 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>");
}
}
The object is created just like C #:
Copy Code code as follows:
Instantiating an Object
var article =new cnblogs.news.Article ();
Assign values to an object's properties
Article.title= "This is the title of the article";
Article.content= "This is the content of the article";
Method of calling Object
Article.show ();
Second, define static class: The so-called static class is the direct invocation of the members of the class, in other words, the members of the class belong to the class, does not belong to the object. Also take article for example, the code is as follows:
Copy Code code as follows:
cnblogs.news.article={
Title: "This is the article headline",
Content: "This is the article contents",
Show:function () {
document.write ("document.write ("<p>" +cnblogs.news.article.content+ "</p>");
}
};
The calling method is similar to C #:
Cnblogs.news.Article.show ();
Here you may have discovered that the so-called JavaScript static class is actually a JSON object, congratulations, correct! ^_^
Third, how to choose:
So when to select the instance class and when to select the static class, as far as personal experience is concerned (not right, please treatise Dao is, how is it possible to ^_^, to develop some weak dependencies on the DOM, requiring complex programs such as tool classes, plug-in classes, structs, and static classes; Conversely, if the program relies on the DOM very strongly, There are often variable transmission, or the structure of the class changes, then select the instance class. Personal comparison of the first scheme, its code style than the second more like C #, I would like to write the C # students will feel so, ^_^.
Author: Uncle Xiang