JavaScript: AJAX basics: Implementation of classes in JavaScript. The Javascript tutorial understands 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. Variables or methods referenced by this pointer in a function will become members of the class. For example:
Function class1 (){ Var s = "abc "; This. p1 = s; This. method1 = function (){ Alert ("this is a test method "); } } Var obj1 = new class1 (); |
The object obj1 is obtained through new class1 (), and the object obj1 automatically obtains the attribute p1 and method method1.
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 to run the class1 function and point the this pointer to the new object;
(3) When a value is assigned to an attribute that does not exist, the interpreter creates this attribute for the object. For example, in class1, when this is executed. when the statement p1 = s is run, a property p1 is added and the value of the variable s is assigned to it. 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, and the code 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. method1 = function (){ Alert ("this is a test method "); } |
Each time method1 creates a class1 instance, it is created once, resulting in a waste of memory. The next section describes the mechanism for defining another type: prototype object, which can solve the disadvantages of defining class members in constructor.
[1] [2] [3] Next page