Ajax basics: Implementation of classes in Javascript

Source: Internet
Author: User
Understanding the implementation mechanism of Classes

In JavaScript, you can use the function keyword to define a "class" and how to add members to the class. All variables or methods referenced by this pointer in a function become members of the class,

For example:   Function CLS (){
VaR Str = " ABC " ;
This . Txt = STR;
This . Display = Function (){
Alert ( " This is a test method " );
}
}

VaR OBJ = new Cls ();
The object obj is obtained through new Cls (), and the object OBJ automatically obtains the TXT attribute and the display method.

In JavaScript, the function itself is defined as a class constructor. The following describes how to create an object by using new, based on the nature of the object and the usage of the new operator.

(1) An empty object is created when the interpreter encounters the new operator;
(2) start running the CLS function and point the this pointer to the newly created object;
When struct = STR, a TXT attribute is added and the STR value is assigned to the variable. In this way, function execution is the process of initializing this object, that is, the role of the constructor;
(4) After the function is executed, the new operator returns the initialized object.

Through this process, the basic object-oriented mechanism is implemented in JavaScript. It can be seen that in Javascript, the function definition is actually an object constructor, which is completed through functions. The disadvantage of this method is:
· Put all initialization statements and member definitions together,CodeThe logic is not clear enough to implement complicated functions.
· Every time you create a class instance, you must execute a constructor. The attributes and methods defined in the constructor are repeatedly created,
For example:
This. Display = function (){

Alert ("this is a test method ");
}

Each time the display creates a CLS instance, it is created once, resulting in a waste of memory. Next we will introduce another type definition mechanism: Prototype object, which can solve the disadvantages of defining class members in constructor.

Define class members using prototype objects
Prototype object. When a new function is created, the members of this object are automatically assigned to the created object. For example: <Script language = " Javascript " Type = " Text/JavaScript " >
< ! --
// Define a class with only one property Caption
Function CLS (){ This . Caption = 1 ;}
// Define a new member for the class using the prototype attribute of the Function
Cls. Prototype. showcaption = Function (){
Alert ( This . Caption );}
// Create an instance of CLS
VaR OBJ = New CLS ();
// Call the showcaption method defined by prototype
OBJ. showcaption ();
  // -->
< / SCRIPT>

Prototype is a javascript object that can be used to add, modify, and delete methods and properties for a prototype object. To add a member definition for a class.

After learning about the prototype object of the function, let's take a look at the new execution process.
(1) create a new object and point this pointer to it;
(2) assign all the members of the prototype object of the function to this new object;
(3) execute the function body to initialize the object;
(4) return the object created in (1.

Compared with the execution process of new introduced in the previous section, prototype is used to initialize the object, which is also consistent with the prototype literal meaning. It is the prototype of the instance of the corresponding class. This initialization process occurs before the execution of the function body (constructor). Therefore, you can call the attributes and methods defined in prototype within the function body, for example: <Script language = " Javascript " Type = " Text/JavaScript " >
< ! --
  // Define a class with only one property Caption
  Function CLS (){
This . Caption = 1 ;
This . Showcaption ();
}
  // Define a new member for the class using the prototype attribute of the Function
Cls. Prototype. showcaption = Function (){
Alert ( This . Caption );}
  // Create an instance of CLS
  VaR Obj1 = New CLS (); //
-- >
< / SCRIPT>

Compared with the previous code, the showcaption method defined in prototype is called internally in CLs, so a dialog box is displayed during the object construction process. The value of the caption attribute is 1.
It should be noted that the definition of the prototype object must be prior to the statement for creating the class instance, otherwise it will not work, for example: <Script language = " Javascript " Type = " Text/JavaScript " >
< ! --
// Define a class with only one property Caption
  Function CLS (){
This . Caption = 1 ;
This . Showcaption ();
}
  // Create an instance of CLS
  VaR OBJ = New CLS ();
  // After creating an instance statement, use the prototype attribute of the function to define a new member for the class, which is only valid for the objects created later.
Cls. Prototype. showcaption = Function (){
Alert ( This . Caption );}
  // -->
< / SCRIPT>

This code will produce a runtime error, indicating that the object does not have the showcaption method, because the method is defined after the statement of a class is instantiated.

It can be seen that prototype objects are dedicated to design class members and are closely related to a class. In addition, prototype also has an important attribute: constructor, which indicates reference to the constructor, for example:
Function Cls (){
Alert (1 );

}
Cls. Prototype. Constructor ();
// Call the constructor of the class

After this code is run, a dialog box is displayed, showing the text "1". It can be seen that a prototype is closely related to the definition of a class. Actually: Cls. Prototype. constructor = Cls.

We have already introduced how to define a class, how to initialize an instance of a class, and how to add a member to the function body defined by the function, and how to define a class member using prototype, the programming code is messy. How can we define classes in a clear way? The following provides a variety of implementation modes.

In JavaScript, due to the flexible nature of the object, you can add members to the class in the constructor, which increases the flexibility and complexity of the Code. To improve code readability and development efficiency, we can use this type of member definition instead of prototype object. In this way, function is defined as a class constructor, in line with the implementation of the traditional meaning class: the class name and the constructor name are the same. For example:   Function CLS (){
// Constructor
}
// Member Definition
Cls. Prototype. someproperty = " Sample " ;
Cls. Prototype. somemethod = Function (){
// Method implementation code
}

although the above Code has clearly defined the class, CLS is required for every attribute or method defined. prototype, not only the code size increases, but also the ease of coding is not enough. For further improvement, you can use the construction method of the non-type object to specify the prototype object, so as to implement the member definition of the class:

code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/

--> // define a class
CLS function Cls () {
/// constructor
}

// define class members by specifying prototype objects
class1.prototype = {< br> someproperty: " sample " , somemethod: function () {
/// method code
},
... // other attributes and methods.
}

The above Code defines CLS in a clear way, and constructor is implemented directly by class name, while Members are defined by non-type objects, all attributes and methods are implemented in the form of a list, and attribute values can be initialized while being defined. This is more like the implementation of classes in traditional object-oriented languages. Only the member definitions of constructors and classes are divided into two parts. This can be seen as a fixed pattern for defining classes in Javascript, which is easier to understand during use.

Note: mutual reference between members of a class must be performed using the this pointer. For example, in the somemethod method in the preceding example, to use the property someproperty, you must use this. in the form of someproperty, because every property and method in Javascript is independent, they are linked to an object through the this pointer.

Related Article

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.