SoFunction
Updated on 2025-04-10

javascript object-oriented JavaScript class

In the previous sectionJavaScript object-oriented namespaceThis section talks about how to define a JavaScript namespace. This section talks about a concept that follows - class. Although there is no class keyword in JavaScript, as developers, we must have this idea. In C#, classes can be divided into instance classes and static classes, and so does JavaScript.


1. Define the instance class: In the previous section, I defined a namespace, and now define a class named Article under this namespace:
Copy the codeThe code is as follows:

=function(){
var _this=this;
=null;
=null;
=function(){
("<h1>"+_this.title+"</h1>");
("<p>"+_this.content+"</p>");
}
}

Creating objects is the same as C#:
Copy the codeThe code is as follows:

// Instantiate an object
var article =new ();
// Assign values ​​to the object's attributes
="This is the title of the article";
="This is the content of the article";
// Call the object method
();

2. Defining a static class: The so-called static class is to directly call the members of the class. In other words, the members of the class belong to the class and do not belong to the object. Take Article as an example, the code is as follows:
Copy the codeThe code is as follows:

={
title: "This is the title of the article",
content: "This is the content of the article",
show:function(){
("<h1>"++"</h1>");
("<p>"++"</p>");
}
};

The call method is also similar to C#:
();
You may have discovered that the so-called JavaScript static class is actually a json object. Congratulations, you have the answer correctly! ^_^
Three, how to choose:
So when to choose an instance class and when to choose a static class? In terms of personal experience (if you say it correctly, please correct it, and you can do whatever you want ^_^), develop some programs that have weak dependence on dom and require strong reuse type, such as tool classes, plug-in classes, structures, and use static classes; on the contrary, if the program has strong dependence on dom, variables are often passed around, or changes to the structure of the class, then choose an instance class. I personally prefer the first solution, and its code style is more like C# than the second one. I think students who are used to writing C# will also think this way, ^_^.
Author: Uncle Xiang