Application of object-oriented programming in javascript

Source: Internet
Author: User
For people who are engaged in or planning to engage in programming, object-oriented is a familiar word. Almost everyone can list some object-oriented programming languages, such as C ++, JAVA, c. In fact, object-oriented thinking is independent of programming languages. For example, in C #, in a static class static method, a series of static functions are called according to procedural development, it is hard to say that this is object-oriented programming. On the contrary, excellent javascript libraries such as jquery and extjs fully reflect the object-oriented design philosophy. This article does not intend to discuss whether javascript can be regarded as an object-oriented programming language. This issue should be paid attention to by people who pay attention to the Chinese examination, here I will simply explain how to use object-oriented programming ideas in javascript.
Object-oriented objects must first have objects. Creating an object in javascript is very simple:

The Code is as follows:


Var o = {};


In this way, an object is generated. We can easily add attributes and methods to this object:

The Code is as follows:


O. name = "object name ";
O. showName = function (){
Alert (o. name );
}


However, most people prefer to put the attributes and methods of objects in a pair of {} defined objects:

The Code is as follows:


Var o = {
Name: "object name ",
ShowName: function (){
Alert (o. name );
}
}


There are two access attributes and methods:

The Code is as follows:


Alert (o. name );
O. showName ();


This method is common. This method also applies to calling object attributes and methods in C. There is also a special method in javascript that uses the attribute or method name as the index for access:

The Code is as follows:


Alert (o ["name"]);
O ["showName"] ();


This seems to be similar to Kong Yiji's "there are several ways to write fennel". In fact, few people use indexes to call the attributes or methods of objects.
In addition to our custom attributes and methods, our object also has a constructor attribute, toString () and other methods. These attributes and methods are built into the Object, and all objects have these attributes and methods. The constructor attribute points to the constructor that constructs the object. We didn't use constructors to create objects. In fact, js interpreters use Object constructors. If we define a constructor, we can use this constructor to create an object, so that the created object has the same attributes and methods, this is a bit object-oriented. Let's start with a simple example to see how to create a constructor:

The Code is as follows:


Function Person (name, sex, age ){
This. name = name;
This. sex = sex;
This. age = age;
This. showInfo = function (){
Alert ("name:" + this. name + "Gender:" + this. sex + "age:" + this. age );
}
}


We have defined a constructor named "Person". This constructor has three attributes and one method. The constructor can generate an object and call the method easily:

The Code is as follows:


Var zhangsan = new Person ("James", "male", 18 );
Zhangsan. showInfo ();


After running, a dialog box is displayed, showing the information of the person named James:

We can also look at the constructor attribute of the object to see if the constructor of zhangsan is defined as Person:

The Code is as follows:


Alert (zhangsan. constructor );


Result

We can see that it is our Person constructor.
However, this is still a problem. Every time we construct an object, we will allocate memory space for attributes and methods in the memory. In fact, all objects can use the same method, there is no need to have copies of multiple methods, which wastes some memory space. Now that we are aware of this problem, let's think about how to solve it. A natural idea is that since we only want to allocate memory space for a method, we can set a value to identify whether the method's memory space has been allocated, modify the constructor as follows:

The Code is as follows:


Function Person (name, sex, age ){
This. name = name;
This. sex = sex;
This. age = age;
If (typeof Person. _ initialized = "undefined "){
This. showInfo = function (){
Alert ("name:" + this. name + "Gender:" + this. sex + "age:" + this. age );
}
Person. _ initialized = true;
}
}


Here, we use a member _ initialized to indicate whether the method has been allocated memory space. When the first object is constructed, _ initialized is not defined, so our judgment statement is true. In this case, the method is defined and the memory space is allocated, then, set the value of _ initialized to true to indicate that the memory space of the method has been allocated. When the second object is constructed, the judgment will not be performed again, and the memory space will not be allocated again. It seems that there is no problem. Run it and check that the information of Michael Jacob is still displayed normally. Although it is not hard, it solves a small problem. Let's celebrate it. I want to have a big dinner. She hasn't started yet. a mm named Li Si also wants her personal information to pop up on the computer. OK. It's easy. Construct an object and call the showInfo method:

The Code is as follows:


Var lisi = new Person ("Li Si", "female", 28 );
Lisi. showInfo ();


In order to take care of MM, we put this section in front of Michael Jacob. MM information is correctly displayed, but Michael's information is missing. John is not happy now, and the ranking is placed behind MM, but he must have a name. I am a programmer, but it seems that I can't eat it. Change the bug first. When firebug is enabled, an error occurs when MM information is displayed. The prompt is zhangsan. showInfo is not a function. Set the breakpoint. After constructing the zhangsi object, the showInfo method is not found. Although the showInfo method has only one method, it exists in the first object, and the second object cannot be accessed. So how can we share the same function with the objects produced by the same constructor? Prototype in javascript provides us with this function. According to the javascript specification, each constructor has a prototype attribute for inheritance and attribute sharing. Our showInfo method can also be seen as an attribute pointing to a function reference. Now we use prototype to share our methods. The code changes are simple. Change this. showInfo to Person. prototype. showInfo. The changed code is as follows:

The Code is as follows:


Function Person (name, sex, age ){
This. name = name;
This. sex = sex;
This. age = age;
If (typeof Person. _ initialized = "undefined "){
Person. prototype. showInfo = function (){
Alert ("name:" + this. name + "Gender:" + this. sex + "age:" + this. age );
}
Person. _ initialized = true;
}
}


Use this constructor to generate two objects:

The Code is as follows:


Var lisi = new Person ("Li Si", "female", 28 );
Lisi. showInfo ();
Var zhangsan = new Person ("James", "male", 18 );
Zhangsan. showInfo ();


After running the command, the information of Li Si is displayed, followed by information of Zhang San. Now both of them are satisfied. Unfortunately, my back-to-pot meat is already cold.

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.