Object-oriented JScript
In the client application of the web page, JS has become an indispensable part. Traditionally, the application of JS is completely based on process model, in which the usage of ordinary statements and global functions is most common. When the number of code is gradually increased, the maintenance of the entire project has become difficult, and the logic has gradually exceeded the control of the designer. At this time, we need to borrow software engineering to manage the project. The foundation of modern software engineering is a component-based, objective programming, and the program design process of UML design guidance is in an orderly manner. What is distressed is that when the concept of modern software engineering is infiltrated into the Web project, it has encountered a lot of problems, and there is almost no way to play its power.
What is the root of the problem? It is not an effective way to organize the JS program so that it can follow some basic object-oriented ideas. However, JS is not a way to reflect these ideas. This article tries to use certain special organization to make JS meet the basic object-oriented characteristics, and put a pad for further application models of software engineering.
Some classes are built in JScript, such as String, Array, Math, etc., users can directly vary from these classes and use their properties and methods. With this, JS can't say the characteristics of object-oriented language. An object-oriented language should have basic characteristics such as packaging, inheritance, polymorphism. JScript does not directly provide methods of implementing these features, but not completely unable.
First, the package in JS
An object-oriented language should allow the user to create a custom type, this JS is done, but its custom type is not qualified with a class, but as function, this function is equivalent to the constructor in other languages. In the custom type, the user can add an attribute and method. However, JS is not explicitly available to public, private, protected, etc., and no status defined by STATIC is provided. The following examples are creating a custom type and implementing a variety of defined methods one by one.
Example 1-1: This example demonstrates the process of creating and using a custom type containing properties and methods. In this example, we created a class called MyClass, which contains a name property and a showname method, then instantiates this class, that is, the method can be called, using the properties. Note that the methods and properties defined in the class should be bound to this class using the THIS keyword, and the binding name is used to access, not by the actual name.
Function Myclass (Name)
{
THIS.NAME = Name;
this.Showname = WriteName;
Function WriteName ()
{
Document.write (this.name);
Document.write ("
");
}
}
->
script>
hEAD>
Var myclass = new myclass ("tom");
Myclass.showname ();
Document.write (myclass.name);
Document.write ("
");
Myclass.name = "jerry"; myclass.showname ();
->
script>
body>
html>
[Ctrl A All Select Tips: You can modify some code first, press Run]
Example 1-2: This example demonstrates the implementation of public and private access. In this example, we modified the MyClass class in the previous example, extending it into two attributes and two methods. Note that PrivateName declaration, it does not bind to this class, so there is only a local scope, the life period is only in this class, if it is called in the class method, it is possible to call it normally (call time is not Add a THIS keyword). Similarly, there is no binding method only to call internal calls. Therefore, the public and private definitions in JS can be implemented in this way.
Function Myclass (Pubname, Privname)
{
Var privateename = privname
this.publicname = public;
This.Showname = WritepublicName;
Function writepublicName ()
{
Document.write (this.publicName);
Document.write ("
");
//document.write (Private);
}
Function WritePrivateName ()
{
Document.write (PrivateName);
Document.write ("
");
}
// WritePrivateName ();
}
->
script>
hEAD>
Var myclass = new myclass ("tom", "cat");
Document.write (myclass.publicname);
Document.write ("
");
//Document.write(Myclass.privateename);
Myclass.showname ();
//myclass.writeprivateename ();
Myclass.publicName = "jerry";
Myclass.showname ();
Document.write ("
");
->
script>
body>
html>
[Ctrl A All Select Tips: You can modify some code first, press Run]
Here, you need to pay attention to a phenomenon. Since JS uses the class itself as a constructor, it will execute the statement one by one by instantiation, retain the method definition, and always execute the entire function. Therefore, the WritePrivateName () of this example is released, and if the statement is performed normally, it will run when the MyClass class is instantiated.
Example 1-3: This example demonstrates the implementation of static defined. In this example, we modify the MyClass class to a class with a normal property, a static property and two static methods. This class can be instantiated, which is only accessible to the normal attributes defined in the class. When not instantiated Similar to C , the initialization of static members needs to be carried out outside of the class.
Function myclass ()
{
THIS.NAME = "CAT";
}
Myclass.number = 0;
Myclass.addnumber = function ()
{
Myclass.number ;
Document.write ("One Had Been Added to Number.");
Document.write ("
");
}
Myclass.shownumber = function ()
{
Myclass.addnumber ();
Document.write (myclass.number);
Document.write ("
");
//document.write(MYClass.Name);
}
->
script>
hEAD>
Myclass.addnumber ();
Myclass.shownumber ();
Var myclass = new myclass ();
Document.write (myclass.name);
Document.write ("
");
//document.write(MYClass.Number);
->
script>
body>
html>
[Ctrl A All Select Tips: You can modify some code first, press Run]
Through the above three examples, we can see that JS supports packaging and supports basic access.
Second, the inheritance in JS
Inheritance is an effective way to extend extensions in object-oriented languages. JS does not provide an extends keyword or ":" operator for implementing inherited, but because it is a dynamic language, you can add it when needed Properties and methods. The implementation of the inheritance mechanism in the following example is based on this principle.
Example 2-1: This example demonstrates a method of deriving a subclass from the base class. The object of the base class is created in the subclass, which adds new properties and methods to it, and then returns it as a result of the subclass constructor to get the subclass object. Sub-objects have more attributes and methods than base classes, assign more memory space. Note the value of each output constructor attribute, found that they are all returned two-class constructor, which is not surprising, because the constructor of the subclass is finally returned, the new attribute, the base class of the new method Objects, the JS execution environment will still think it is a base class object.
Function BaseClass (Name)
{
This.Typename = Name; this.writebasename = writebasename;
Function Writebasename ()
{
Document.write ("BASE NAME:");
Document.write (this.Typename);
Document.write ("
");
Document.write (this.constructor);
Document.write ("
");
}
}
Function DeriveClass (Name)
{
VAR Base = New Baseclass ("cat");
Base.name = name;
Base.writeeriveName = WriteeriveName;
Function WriteeriveName ()
{
Document.write ("Derived Name:");
Document.write (base.name);
Document.write ("
");
Document.write (this.constructor);
Document.write ("
");
}
Return Base;
}
->
script>
hEAD>
Var cat = new deriveclass ("tom");
Cat.writebasename ();
Cat.WriteeriveName ();
->
script>
body>
html>
[Ctrl A All Select Tips: You can modify some code first, press Run]
Example 2-2: This example demonstrates a method of derived a subclass from two different base classes. The objects of two base classes are created in the subclass, and all attributes and methods of one of them are added to another, and then the latter is returned as the result of the subclass constructor to obtain a sub-class object. With this way, multiple inheritance is achieved. There is a point of attention, and if the same name variable or method is included in different base classes, it is necessary to specify which as actual binding.
Function Apple ()
{
this.smelllike = "apple";
This.Showsmell = showsmell;
Function showsmell ()
{
Document.write ("SMELL LIKE:");
Document.write (this.smelllike);
Document.write ("
");
}
}
Function pear ()
{
THIS. Tastelike = "pear";
THIS.SHOWTASTE = ShowTaste;
Function showtaste ()
{
Document.write ("Taste Like:");
Document.write (this.tastelike);
Document.write ("
");
}
}
Function Appler ()
{
Var result = new apple ();
Var pear = new pear ();
Result.tastelike = pear.tastelike;
Result.ShowTaste = pear.showtaste;
Return Result;
}
->
script>
hEAD>
VAR Appler = new applepear ();
ApplePear.showsmell ();
ApplePear.showTaste ();
->
script>
body>
html>
[Ctrl A All Select Tips: You can modify some code first, press Run]
It can be seen from the above two examples that JS actually supports the mechanism of inheritance, but this mechanism requires more manual control.
Since it comes to inheritance, it will be discussed by the way, and its role is to make the defined variable or method cannot be called by instance of the class, but can be sent to be called. When I wrote this article, I have spent a lot of time to consider whether it is possible to use JS simulation. Later, since the public is implemented by the specified binding, then it cannot be created. The relationship between binding and non-bound is not well used in this way. Remember again, protected is almost all of the language that is implemented. In the target code or intermediate code hierarchy, it is very important to effectively cooperate with the software engineering theory, but JS is a pure interpretation language, the level of source code, does not have a valid module protection mechanism, anyone can freely Modifying the code, so that the protected key is completely free.
C and other languages have a special class: interface. The role of the interface is to provide specifications, constraints, which specifies the collection of methods that inherited this interface. We can certainly implement such a mechanism, when the class inherits the interface, check whether it implements all the methods in the interface, or whether the declarations of these methods are provided, but this approach is not necessary. When inheriting this interface, according to this inheritance mechanism above, an object of the interface will be created directly (some language is disabled from instantiating), this time, it already contains the method set in the interface. Even if they do not redefine these methods and bind them, they have been declared, and JS does not provide a mechanism to identify abstract methods, whether the method in the interface has been implemented.
Triple, the polymorphism in JS
Polymorphism enables objects to determine the actual call when runtime. Since JS is a dynamic language, it is supported when it is binding, discussing its polymorphism. It doesn't great significance. JS does not support the Virtual keyword, and the Virtual keyword does not have obvious use in the current JS. The most fundamental point, JS can change the data type at runtime, and can obtain the methods it owns according to the new type, and ignore the impact of the original type.
Example 3-1: This example creates a base class with one subclass, with a synonymous method, instantiates the base classes and subclats and calls this method, respectively, and the results of the display will vary depending on the class of the method. The reason is very simple, because this "inheritance" mechanism used by examples itself is implemented using the dynamic characteristics of the JS language. When a class instantiates, it has known what methods you have, and it doesn't care from these methods Which class inherits, just call them as a normal member method, so the same name method for each class is belonging to him. Furthermore, JS is a weak type of language. When its variable declares does not know his type, it does not know what type of it will be initialized, what type of value gives it, it is what type variable. The two statements that have been commented in this example will illustrate this problem: JS can impart a sub-class variable to the base class variable (this feature in the language of C ) can also be achieved. The base class variable is assigned to subclass variables (generally not allowed in static language because additional information) is missing.
Function BaseClass (Name)
{
this.Typename = name;
THIS.WRITENAME = WriteName;
Function WriteName ()
{
Document.write ("BASE NAME:");
Document.write (this.Typename);
Document.write ("
");
Document.write (this.constructor);
Document.write ("
");
}
}
Function DeriveClass (Name)
{
VAR Base = New Baseclass ("cat");
Base.name = name;
Base.writename = WriteName;
Function WriteName ()
{
Document.write ("Derived Name:");
Document.write (base.name);
Document.write ("
");
Document.write (this.constructor);
Document.write ("
");
}
Return Base;
}
->
script>
hEAD>
VAR Base = New Baseclass ("cat");
Base.writename ();
VAR Derive = New DeriveClass ("Tom");
Derive.writename ();
/ *
Base = deer;
Base.writename ();
* /
/ *
Derive = base;
Derive.writename ();
* /
->
script>
body>
html>
[CTRL A All Selection Tips: You can modify some code first, then press Run] Fourth, summary
Comprehensive analysis, JS reluctance can be an object-oriented language, and therefore, it is also possible to apply some software engineering ideas to the development, so that the architecture of the entire project is stable and logical. The predecessors of the 51JS Forum have made great efforts. He designed JS's object-oriented characteristics into a rule, imitating Java's bag-class structure, and has made some common class libraries supported by this rule. After a paragraph The effort and improvement of time is already possible to initially apply.
Adidal: Write this article from a inspiration, when learning design mode, I think of many irregularities in the current web programming, most people still use traditional process structures to control the entire project, the more The bigger it is, it is often a feeling of feeling. The confusing design, hidden everywhere, all this is destined to avoid? So I tried to reopeize JS with object-oriented ideas, and expect to apply some design patterns to the web program design, let the architecture of the entire project under the premise of interface design and transaction separation Tended to be reasonable, stable. When I wrote this article, I didn't know how much I learned to JS, nor I didn't know if my understanding contained a serious mistake. All this is just an exploration, and I hope everyone can enlighten, or give good advice. . I am a student of the Southeast University Computer Series. It happened that this semester software architecture course teacher requires free selection of a paper, spent a week, I hope that I have not let the teacher disappointed, huh, huh.