Object-oriented JScript (top)

Source: Internet
Author: User
In client applications on the web page, JS has become an indispensable part. Traditional JS applications are completely based on the process model. In this model, common statements and global functions are most commonly used. When Code As the number of projects increases, the maintenance of the entire project becomes difficult, and the logic is gradually beyond the control of the designers. At this time, we need to use the concept of software engineering to manage the project. The foundation of modern software engineering is componentized and object-oriented. Program DESIGN: the program design process guided by the UML design diagram is carried out in an orderly manner. It is distressing that when the concept of modern software engineering is infiltrated into web projects, there is a big problem and there is almost no way to exert its power.

What is the root cause of the problem? There is no effective way to organize JS programs so that they can follow some basic object-oriented ideas. However, JS is not unable to reflect these ideas. This article attempts to use some special organization methods to make JS conform to basic object-oriented features, it paves the way for further application of some design patterns of software engineering.

JScript has built-in classes, such as string, array, and math. You can create objects from these class instances and use the attributes and methods. With this alone, JavaScript cannot be said to conform to the characteristics of object-oriented languages. An object-oriented language should have encapsulation, inheritance, polymorphism, and other basic features. JScript does not directly provide methods to implement these features, but it is not completely impossible.

1. js Encapsulation
An object-oriented language should allow users to create custom types. This is done by JS, but its custom types are not limited by class, but are used as functions, this function serves as a constructor in other languages. In a custom type, you can add attributes and methods. However, access restrictions such as public, private, and protected are not explicitly provided in JS, and scope restrictions such as static are not provided. The following examples illustrate how to create a custom type and implement various limits one by one.

Example 1-1: This example shows how to create and use a custom type that contains attributes and methods. In this example, a class named myclass is created, which contains a name attribute and a showname method. Then, the class is instantiated to call the method, use the attributes. Note: The methods and attributes defined in the class should be bound to this class using the this keyword. when calling the class, use the bound name for access, instead of the actual name.<textarea style="font-family: 'Courier New',Courier,monospace" name="runcode0" rows="12" cols="95"><HTML> <br/> <pead> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> function myclass (name) <br/>{< br/> This. name = Name; <br/> This. showname = writename; <br/> function writename () <br/> {<br/> document. write (this. name); <br/> document. write ("<br/> "); <br/>}< br/> --> <br/> </SCRIPT> <br/> </pead> <br/> <body> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> var myclass = new myclass ("Tom"); <br/> myclass. showname (); <br/> document. write (myclass. name); <br/> document. write ("<br/>"); <br/> myclass. name = "Jerry"; <br/> myclass. showname (); <br/> --> <br/> </SCRIPT> <br/> </body> <br/> </ptml></textarea>
Tip: you can modify some code before running

Example 1-2: This example demonstrates the implementation of public and private access restrictions. In this example, we modified the myclass class in the previous example and expanded it into two attributes and two methods. Note that the privatename declaration is not bound to this class, so it only has a local scope. The life cycle is only in this class. If you call it in the class method, yes, it can be called normally (this keyword is not added during the call ). Similarly, methods without binding can only be called within the class. Therefore, the public and private limits in JS can be implemented in this way.<HTML> <br/> <pead> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> function myclass (pubname, privname) <br/>{< br/> var privatename = privname; <br/> This. publicname = pubname; <br/> This. showname = writepublicname; <br/> function writepublicname () <br/>{< br/> document. write (this. publicname); <br/> document. write ("<br/>"); <br/> // document. write (privatename); <br/>}< br/> function writeprivatename () <br/>{< br/> document. write (privatename); <br/> document. write ("< Br/> "); <br/>}< br/> // writeprivatename (); <br/>}< br/> --> <br/> </SCRIPT> <br/> </pead> <br/> <body> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> var myclass = new myclass ("Tom", "cat"); <br/> document. write (myclass. publicname); <br/> document. write ("<br/>"); <br/> // document. write (myclass. privatename); <br/> myclass. showname (); <br/> // myclass. writeprivatename (); <br/> myclass. publicname = "Jerry"; <br/> myclass. showname (); <br/> document. write ("<br/>"); <br/> --> <br/> </SCRIPT> <br/> </body> <br/> </ptml>
Tip: you can modify some code before running

Here, we need to note that, since JS regards the class itself as a constructor, it will execute the statements one by one during instantiation and keep the method definitions in it, the entire function has been executed. Therefore, if the writeprivatename (); statement commented out in this example is executed normally, it will be run during the myclass class instantiation.

Example 1-3: This example demonstrates the implementation of static limitation. In this example, we change the myclass class to a class with a common attribute, a static attribute, and two static methods. This class can be instantiated, and only common attributes defined in the class can be accessed. When the class name is used for access without instantiation, the static methods and static attributes in the class can be accessed. Static methods can only access static attributes. Similar to C ++, static member initialization must be performed outside the class.<HTML> <br/> <pead> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> function myclass () <br/>{< br/> This. name = "cat"; <br/>}</P> <p> myclass. number = 0; <br/> myclass. addnumber = function () <br/>{< br/> myclass. number ++; <br/> document. write ("one had been added to number. "); <br/> document. write ("<br/>"); <br/>}; <br/> myclass. shownumber = function () <br/>{< br/> myclass. addnumber (); <br/> document. write (myclass. number); <br/> document. write ("<br/>"); <br/> // docum Ent. write (myclass. name); <br/> }; <br/> --> <br/> </SCRIPT> <br/> </pead> <br/> <body> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> myclass. addnumber (); <br/> myclass. shownumber (); <br/> var myclass = new myclass (); <br/> document. write (myclass. name); <br/> document. write ("<br/>"); <br/> // document. write (myclass. number); <br/> --> <br/> </SCRIPT> <br/> </body> <br/> </ptml>
Tip: you can modify some code before running

Through the above three examples, we can see that JS supports encapsulation well and supports basic access restrictions.

Ii. Inheritance in JS
Inheritance is an effective way to extend existing types in object-oriented languages. js does not provide extends keywords or ":" operators for inheritance. However, because it is a dynamic language, you can add attributes and methods as needed. In the following example, the implementation of the Inheritance mechanism is based on this principle.

Example 2-1: This example demonstrates how to derive a subclass from the base class. The subclass creates a base class object, adds new attributes and methods to it, and then returns the result as a subclass constructor to obtain the subclass object. Subclass objects have more attributes and methods than base class objects and allocate more memory space. Note the value of the constructor attribute output each time. It is not surprising that the returned constructor is a base class constructor, because the final returned result of the subclass constructor is a base class object with new attributes and methods added, the JS execution environment still considers it as a base class object.<HTML> <br/> <pead> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> function baseclass (name) <br/>{< br/> This. typename = Name; <br/> This. writebasename = writebasename; <br/> function writebasename () <br/>{< br/> document. write ("base name:"); <br/> document. write (this. typename); <br/> document. write ("<br/>"); <br/> document. write (this. constructor); <br/> document. write ("<br/>"); <br/>}< br/> function deriveclass (name) <br/>{< br/> var base = new baseclass ("Cat"); <br/> base. name = Name; <br/> base. writederivename = writederivename; <br/> function writederivename () <br/>{< br/> document. write ("derived name:"); <br/> document. write (base. name); <br/> document. write ("<br/>"); <br/> document. write (this. constructor); <br/> document. write ("<br/>"); <br/>}< br/> return base; <br/>}< br/> --> <br/> </SCRIPT> <br/> </pead> <br/> <body> <br/> <script language = "javascrip T "> <br/> <! -- <Br/> var cat = new deriveclass ("Tom"); <br/> cat. writebasename (); <br/> cat. writederivename (); <br/> --> <br/> </SCRIPT> <br/> </body> <br/> </ptml>
Tip: you can modify some code before running

Example 2-2: This example demonstrates how to derive a subclass from two different base classes. The subclass creates two base class objects, adds all the attributes and methods of one of them to the other, and then returns the result of the latter as the subclass constructor, obtain the subclass object. In this way, multiple inheritance is realized in disguise. Note that if different base classes contain variables or methods of the same name, you need to specify which one is actually bound.<HTML> <br/> <pead> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> function Apple () <br/> {<br/> This. smelllike = "apple"; <br/> This. showsmell = showsmell; <br/> function showsmell () <br/>{< br/> document. write ("smell like:"); <br/> document. write (this. smelllike); <br/> document. write ("<br/>"); <br/>}< br/> function pear () <br/>{< br/> This. tastelike = "Pear"; <br/> This. showtaste = showtaste; <br/> function showtaste () <br/>{< br/> document. write ("Taste Li KE: "); <br/> document. write (this. tastelike); <br/> document. write ("<br/>"); <br/>}< br/> function applepear () <br/>{< br/> var result = new Apple (); <br/> var pear = New Pear (); <br/> result. tastelike = pear. tastelike; <br/> result. showtaste = pear. showtaste; <br/> return result; <br/>}< br/> --> <br/> </SCRIPT> <br/> </pead> <br/> <body> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> var applepear = new applepear (); <br/> applepear. showsmell (); <br/> applepear. showtaste (); <br/> --> <br/> </SCRIPT> <br/> </body> <br/> </ptml>
Tip: you can modify some code before running

The above two examples show that JS actually supports the Inheritance Mechanism, but this mechanism requires more manual control.

When it comes to inheritance, let's take a look at the protected limitation. Its function is to make the variable or method that is defined cannot be called by the instance of the class, but can be called by the derived class. Write this articleArticleI spent a lot of time thinking about whether it is possible to use js to simulate this limitation. Later I found that since public and private limits are implemented by specifying bindings, you cannot create a relationship between binding and not binding, so it is difficult to simulate it in this way. Another thought, protected restrictions are almost all implemented in compiled languages. At the target code or intermediate code level, this limitation is very important. It can be effectively developed with the software engineering theory, but JS is a pure explanatory language,Source codeThere is no effective module protection mechanism at the public level. Anyone can modify the code at will. In this way, the protected keyword is useless.

C ++ and other languages have a special class: interfaces. An interface provides a set of methods required to inherit the class. Of course, we can implement such a mechanism. When a class inherits an interface, we can check whether it implements all the methods in the interface or whether the declaration of these methods is provided. However, this approach is not necessary. When the interface is inherited, an object of the interface will be directly created based on the Inheritance Mechanism Implemented above (in some languages, the interface cannot be instantiated). At this time, it already contains the set of methods defined in the interface. Even if these methods are not re-defined and bound, they are clearly declared, and JS does not provide a mechanism to identify abstract methods, it is unknown whether the methods in the interface have been implemented.

Iii. polymorphism in JS
Polymorphism allows the object to determine the actual method body called at runtime. Because Javascript is a dynamic language that supports runtime binding, discussing its polymorphism does not actually make much sense. JS does not support virtual keywords, and virtual keywords are not of obvious use in current Js. The most fundamental point is that JS can change the data type at runtime, and can obtain the methods it has at any time based on the new type, ignoring the influence of the original type.

Example 3-1: In this example, a base class and a subclass have a method of the same name, instantiate the base class and subclass respectively, and call this method, the displayed result varies with the class to which the method belongs. The reason is very simple, because the "inheritance" mechanism used in this example is implemented by using the dynamic characteristics of the JS language. When a class is instantiated, it knows what methods it has, it does not care which class these methods inherit from, but calls them as common member methods. Therefore, the same name method called by each class belongs to itself. Furthermore, JS is a weak type language. When declaring its variables, it does not know its own type, or the type of value to be initialized or assigned to it, it is a type of variable. The two paragraphs commented out in this example illustrate this problem: JS can assign subclass variables to the base class variables at runtime (this feature is critical to implementing polymorphism in C ++ and other languages ), you can also assign the base class variable to the subclass variable (this is generally not allowed in static languages because additional information is missing ).<HTML> <br/> <pead> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> function baseclass (name) <br/>{< br/> This. typename = Name; <br/> This. writename = writename; <br/> function writename () <br/> {<br/> document. write ("base name:"); <br/> document. write (this. typename); <br/> document. write ("<br/>"); <br/> document. write (this. constructor); <br/> document. write ("<br/>"); <br/>}< br/> function deriveclass (name) <br/>{< br/> var base = new baseclass ("cat"); <br/> Base. name = Name; <br/> base. writename = writename; <br/> function writename () <br/> {<br/> document. write ("derived name:"); <br/> document. write (base. name); <br/> document. write ("<br/>"); <br/> document. write (this. constructor); <br/> document. write ("<br/>"); <br/>}< br/> return base; <br/>}< br/> --> <br/> </SCRIPT> <br/> </pead> <br/> <body> <br/> <script language = "JavaScript"> <br/> <! -- <Br/> var base = new baseclass ("cat"); <br/> base. writename (); <br/> var derive = new deriveclass ("Tom"); <br/> derive. writename (); <br/>/* <br/> base = derive; <br/> base. writename (); <br/> */<br/>/* <br/> derive = base; <br/> derive. writename (); <br/> */<br/> --> <br/> </SCRIPT> <br/> </body> <br/> </ptml>
Tip: you can modify some code before running

Iv. Summary
Based on the above analysis, JS is barely an object-oriented language. Therefore, it can also apply some software engineering ideas to development, so that the entire project architecture is stable and the logic is clear. The predecessor of the 51js Forum, Wan Changhua, made great efforts to design JS object-oriented features into a rule that imitates Java's package-class structure, some common class libraries supported by such rules have been made. After some time of efforts and improvement, they can be initially applied.

Note: I wrote this article from an inspiration. When I learned the design model, I think of the many irregularities in Web programming, most people still use the traditional process-based structure to control the entire project. When the project grows, it often feels powerless. Are all chaotic designs and bugs hidden everywhere inevitable? As a result, I tried to review JS with an object-oriented approach and expected to apply some design patterns to WEB programming in the future, with the separation of interface design and transaction processing, the architecture of the entire project tends to be reasonable and stable. When I wrote this article, I did not know how much I knew about JS or whether my understanding included serious errors. It was just an exploration, I hope you can give us some advice or give us some suggestions. I am a senior in the Computer Science Department of Southeast University. It happened that this semester's software architecture course teacher asked me to write a thesis freely, and it took a week, hoping that the teacher would not be disappointed, haha.

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.