JavaScript in Ajax supports object-oriented basics

Source: Internet
Author: User
Tags add date empty eval execution functions string variable
Ajax|javascript| object in the object-oriented thinking, one of the core concepts is the class. A class represents an abstraction of something of a similar nature and, by instantiating a class, can obtain an instance of the class, that is, an object.

The way to define a class in JavaScript is as follows:

function Class1 () {
Definition of class members and constructors
}
Here Class1 is both a function and a class. It can be understood as the constructor of the class, which is responsible for initializing the work.

   use the new operator to get an instance of a class

The new operator has been used before to introduce the basic object, for example:

New Date ();
Represents the creation of a Date object, and date is the class that represents the date, except that this class is provided internally by JavaScript, not by user-defined.

The new operator is not only valid for the internal class, but also for user-defined classes, and for the Class1 defined in the previous section, you can also use new to get an instance:

function Class1 () {
Definition of class members and constructors
}
var obj1=new Class1 ();
Aside from the concept of the class, from the form of code, Class1 is a function, then is not all functions can be used to operate with new? Yes, in JavaScript, functions and classes are concepts that return an object when a new operation is performed on a function. If the class member is not initialized in this function, an empty object is returned. For example:

Define a Hello function
function Hello () {
Alert ("Hello");
}
Get an object by using a new function
var obj=new hello ();
Alert (typeof (obj));


From the results of the operation, the Hello function is executed, and obj also gets a reference to an object. When new is a function, this function is the constructor of the class represented, where the code is considered to initialize an object. The function used to represent a class is also called a constructor.

   use square brackets ([]) to refer to properties and methods of an object

In JavaScript, each object can be thought of as a collection of multiple properties (methods), and referencing a property (method) is simple, such as:

Object name. Property (method) name

You can also refer to the form of square brackets:

Object Name [Property (method) name]

Note that the method name and property name here are a string, not the original point (?). identifier, for example:

var arr=new Array ();
Add an element to an array
arr["Push"] ("abc");
Get the length of an array
var len=arr["Length"];
The length of the output array
alert (len);

Figure 1
Figure 1 shows the results of the execution.

This shows that the above code is equivalent to:

var arr=new Array ();
Add an element to an array
Arr.push ("abc");
Get the length of an array
var len=arr.length;
The length of the output array
alert (len);
This type of reference property (method) is similar to the array, reflecting the nature of a JavaScript object as a set of attributes (methods).

This usage is appropriate for situations where you are unsure which property (method) to reference, such as an object used to represent user data, and a string that represents the attribute to use, which can be referenced in this way:


!--drop-down list box for selecting user information-->
Select the information you want to view: ages sex
In this code, a Drop-down list box is used to let the user choose which information to view, and the value of each option represents the property name of the user object. If you do not take the form of square brackets, you can use the following code to implement this:

Function Show (SLT) {
if (slt.selectedindex!=0) {
if (slt.value== "age") alert (user.age);
if (slt.value== "sex") alert (user.sex);
}
}
Instead of using the square brackets syntax, you simply write as:

Alert (User[slt.value]);
The square bracket syntax is like a parameter syntax, and a variable can be used to indicate which property of the referenced object. If you do not use this method, and you do not want to use conditional judgment, you can use the Eval function:

Alert (eval ("User.") +slt.value));
Using the properties of the Eval function, a dynamically generated code is executed and the result is returned.

In fact, in front of the collection object of the document, there is a similar use of square brackets, such as referring to a form object named "Theform" in the page, which used to be:

document.forms["Theform"];
can also be rewritten as:

Document.forms.theForm;
The forms object is an internal object, and unlike a custom object, it can also use an index to reference one of its properties.

   dynamically add, modify, and delete properties and methods of objects

The previous article describes how to refer to the properties and methods of an object, and now describes how to add, modify, or delete properties and methods for an object.

In other languages, once an object is generated, it cannot be changed, and to add or modify members to an object must be modified in the corresponding class and instantiated, and the program must be recompiled. JavaScript provides a flexible mechanism to modify the behavior of objects and dynamically add, modify, and delete properties and methods. For example: First Use class object to create an empty object user:

var user=new Object ();
1. Add properties

When the user object does not have any properties and methods, you can add properties to it dynamically, for example:

User.name= "Jack";
user.age=21;
user.sex= "Male";
With the above statement, the user object has three properties: Name, age, and sex. The following three statements are exported:

alert (User.Name);
alert (user.age);
alert (user.sex);
As the code runs, three properties are already fully owned by the user object.

2. Add method

The procedure for adding a method is similar to adding a property:

User.alert=function () {
Alert ("My name is:" +this.name);
}
This adds a method "alert" to the user object that, by executing it, pops up a dialog box to display its name:

User.alert ();

Figure 2
Figure 2 shows the results of the execution.

3. modifying properties and Methods

The process of modifying a property and method is to replace the old attribute with the new one, for example:

User.name= "Tom";
User.alert=function () {
Alert ("Hello," +this.name);
}
This modifies the value of the user Object Name property and the alert method, which changes from the display "My Name is" dialog box to display the "Hello" dialog box.

4. deleting properties and methods

The process of deleting a property and a method is also simple, which is to place it as undefined:

user.name=undefined;
user.alert=undefined;
This deletes the Name property and the alert method.

You can also use square brackets ([]) syntax when adding, modifying, or deleting a property, as with a reference property:

user["Name"]= "Tom";
Another feature of this approach is that you can use a non-identifier string as a property name, such as not allowing a number to begin in an identifier or a space, but you can use it in square brackets ([]) syntax:

user["My Name"]= "Tom";
Note that when you use an attribute with this non identifier as the name, you still need to refer to the brackets syntax:

Alert (user["my Name"]);
and cannot be written as:

Alert (user.my name);
In fact, each object in JavaScript is dynamically variable, which gives programming flexibility and differs from other languages.

   Create an untyped object using the curly braces ({}) syntax

In the traditional object-oriented language, each object will correspond to a class. When the this pointer is mentioned in the previous section, the object in JavaScript is actually a collection of attributes (methods), and there is no concept of a class in the strictest sense. So it provides an easy way to create objects, that is, curly braces ({}) Syntax:

{
Property1:statement,
Property2:statement2,
...,
Propertyn:statmentn
}
The definition of an object is implemented by enclosing multiple properties or methods and their definitions (these properties or methods are separated by commas), and this code directly defines an object that has n attributes or methods, separated by a colon (:) between the property name and its definition. For example:


The first line defines an object obj with no type, which is equivalent to:

var obj=new Object ();
It then defines an object user and its properties and methods. Note that other than the last attribute (method) definition, the other must end with a comma (,). In fact, the method of dynamically adding and subtracting properties can also define an identical user object, which the reader can implement using the method described earlier.

You define objects in this way, and you can also use strings as property (method) names, such as:

var obj={"001": "ABC"}
This defines an attribute "001" for object obj, which is not a valid identifier, so you must use the bracket syntax to reference this property:

obj["001"];
Thus, an untyped object provides an easy way to create an object, which manifests an object as a complete entity in a compact and clear syntax. It also helps to reduce the size of the code, which is especially important for JavaScript code, and reducing the volume means increasing the speed of access.

   prototype prototype Object

Prototype object is an important mechanism to realize object-oriented. Each function is also an object, and their corresponding classes are "function", but they are special, and each function object has a child object prototype. That is, prototype represents the prototype of the function, and the function is a class, prototype is a collection of members representing a class. When you obtain an object of a class by using new, the members of the prototype object become members of the instantiated object.

Since prototype is an object that can be dynamically modified using the methods described in the previous two sections, here's a simple example:

An empty class was defined
function Class1 () {
Empty
}
Modify the prototype object of a class to add method
Class1.prototype.method=function () {
Alert ("It ' s a test method");
}
To create an instance of a class Class1
var obj1=new Class1 ();
method to invoke Obj1
Obj1.method ();

Figure 3 shows the results of the execution.

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.