Various methods for defining classes in JavaScript.

Source: Internet
Author: User
Tags prototype definition

Original link http://blog.csdn.net/avon520/archive/2009/01/17/3819751.aspx
When it comes to object-oriented, we can think of classes, objects, encapsulation, inheritance, and polymorphism. Translated by Cao Li and Zhang Xin in "javascript Advanced Programming Design" (People's post and telecommunications press. Professional JavaScript For Web developers. Let's take a look at various methods of defining classes in JavaScript.

1. Factory method

To create your own classes and objects in Javascript, we must understand that the attributes of objects in javascript can be dynamically defined after an object is created, for example, the following code:

<SCRIPT type = "text/JavaScript">
// Define
VaR ocar = new object ();
Ocar. color = "red ";
Ocar. Doors = 4;
Ocar. showcolor = function (){
Alert (this. Color );
}
// Call
Ocar. showcolor ();
</SCRIPT>

We can easily use ocar objects, but we want to create multiple car instances. We can use a function to encapsulate the above Code: <SCRIPT type = "text/JavaScript">
// Define
Function createcar (){
VaR ocar = new object ();
Ocar. color = "red ";
Ocar. Doors = 4;
Ocar. showcolor = function (){
Alert (this. Color );
}
Return ocar;
}
// Call
VaR ocar1 = createcar ();
VaR ocar2 = createcar ();
Ocar1.color = "black ";
Ocar1.showcolor ();
Ocar2.showcolor ();
</SCRIPT>

By the way, the default member attributes of JavaScript objects are public. This method is called the factory method. We create a factory that can create and return specific types of objects.

This is a bit interesting, but in object orientation, we often use the method of creating objects as follows:

Car car = new car ();

The use of the new keyword has been deeply rooted in the hearts of the people, so it is awkward to use the above method to define, and create new attributes and functions each time a call is made, which is not actually functional. Let's take a look at the class defined in the form of constructor.

2. Constructor

This method looks a bit like a factory function. The specific performance is as follows:

<SCRIPT type = "text/JavaScript">
// Define
Function car (color, doors ){
This. Color = color;
This. Doors = doors;
This. showcolor = function (){
Alert (this. Color );
};
}
// Call
VaR car1 = new car ("red", 4 );
VaR car2 = new car ("blue", 4 );
Car1.showcolor ();
Car2.showcolor ();
</SCRIPT>

It looks like the effect is quite obvious, so there is a difference. It seems a little interesting. When you create an object within the constructor and use the this keyword, It is very friendly to create an object using the new operator. But there is also a problem: every time a new object is created, all attributes will be created, including the creation of functions. That is to say, multiple objects are completely independent. The purpose of defining classes is to share methods and data, but car1 objects and car2 objects are independent attributes and functions. At least we should share the method. This is the advantage of the original mode.

3. Prototype

The prototype attribute of the object shows the prototype on which the new object depends. The method is as follows:

<SCRIPT type = "text/JavaScript">
// Define
Function car (){
};
Car. Prototype. color = "red ";
Car. Prototype. Doors = 4;
Car. Prototype. Drivers = new array ("Tom", "Jerry ");
Car. Prototype. showcolor = function (){
Alert (this. Color );
}
// Call:
VaR car1 = new car ();
VaR car2 = new car ();
Car1.showcolor ();
Car2.showcolor ();
Alert (car1.drivers );
Car1.drivers. Push ("Stephen ");
Alert (car1.drivers); // result: Tom, Jerry, Stephen
Alert (car2.drivers); // result: Tom, Jerry, Stephen

// The prototype definition can be simplified in JSON format:

Car. Prototype =
{
Color: "red ",
Doors: 4,
Drivers: ["Tom", "Jerry", 'safdad'],
Showcolor: function (){
Alert (this. Color );
}
} </SCRIPT>

First, there is no code in the constructor of this Code. Then, you can use the prototype attribute of the object to add a property to define the property of the car object. This method is good, but the problem is that the car object points to the array pointer. Both the car objects point to the same array. One of the objects car1 changes the reference of the attribute object (array) the other object car2 also changes. This is not allowed.

This problem also occurs when the prototype does not contain any initialization parameters, and the constructor Cannot initialize normally. This requires another solution: Hybrid constructor/prototype.

4. Mixed constructor/prototype mode

Using constructor and prototype together makes it very convenient to define classes.

<SCRIPT type = "text/JavaScript">
// Define
Function car (color, doors)
{
This. Color = color;
This. Doors = doors;
This. Drivers = new array ("Tom", "Jerry ");
}

Car. Prototype. showcolor = function (){
Alert (this. Color );
}

// Call:
VaR car1 = new car ('red', 4 );
VaR car2 = new car ('blue', 4 );

Car1.showcolor ();
Car2.showcolor ();

Alert (car1.drivers );
Car1.drivers. Push ("Stephen ");
Alert (car1.drivers); // result: Tom, Jerry, Stephen
Alert (car2.drivers); // result: Tom, Jerry
Alert (car1 instanceof car );

</SCRIPT>

This method puts attributes in the internal definition, and places methods out and uses prototype for definition. Solved the problem of the third method.

This method is actually very friendly, but compared with the Java syntax, there should be some discord, feeling messy, for C ++, we don't feel so troublesome, but developers of C ++ generally seldom involve Javascript. for developers of J2EE, this method is always awkward. The general feeling is not a friendly encapsulation, but the visual encapsulation effect is not very good. To achieve the visual encapsulation effect and achieve the effect of this method, you can also, I personally think it is quite troublesome. That is, the dynamic prototype method.

5. Dynamic Prototype

Developers who are used to other languages feel less harmonious when using a hybrid constructor/prototype. After all, most object-oriented languages visually encapsulate attributes and methods when defining classes. Consider the following C # class:

Class car // class
{
Public String color = "red ";
Public int doors = 4;
Public int MPG = 23;

Public Car (string color, int doors, int mpg) // Constructor
{
This. Color = color;
This. Doors = doors;
This. mpg = MPG;
}
Public void showcolor () // Method
{
Console. writeline (this. Color );
}
}

C # all the attributes and methods of the car class are well packaged. Therefore, when you see this code, you will know what functions it will implement and define the information of an object. People who criticize the mixed constructor/prototype think that finding properties in the constructor memory is not logical. Therefore, they have designed a dynamic prototype method to provide a more friendly encoding style.

The basic idea of the dynamic prototype method is the same as that of the mixed constructor/prototype method. That is, the non-function attributes are defined in the constructor, while the function attributes are defined using the prototype attributes. The only difference is that the location of the object method is assigned. The following is the car class that is rewritten using the dynamic prototype method:

<SCRIPT type = "text/JavaScript">
// Define
Function car (){
This. color = "red ";
This. Doors = 4;
This. Drivers = new array ("Tom", "Jerry ");
If (typeof car. _ initialized = "undefined "){
Car. Prototype. showcolor = function (){
Alert (this. Color );
}
//............
}
// Final definition
Car. _ initialized = true;
}
</SCRIPT>

This constructor remains unchanged until you check whether typeof car. _ initialized is "undefined. This line of code is the most important part of the dynamic prototype method. If this value is not defined, the constructor will continue to define the object method in prototype mode, and then set car. _ initialized to true. If this value is defined (when its value is true, the value of typeof is Boolean), this method will not be created. In short, this method uses the sign (_ initialized) to determine whether any method has been granted to the prototype. This method is created and assigned only once. To make the traditional OOP developers happy, this code looks more like a class definition in other languages.

6 hybrid factory Mode

This method is usually a work und when the previous method cannot be applied. The objective is to create a pseudo constructor and return only new instances of another object. This code looks very similar to the factory function:

Function car (){
VaR otempcar = new object ();
Otempcar. color = "red ";
Otempcar. Doors = 4;
Otempcar. mpg = 23;
Otempcar. showcolor = function (){
Alert (this. Color );
}
Return otempcar;
}

Unlike the classic method, this method uses the new operator to make it look like a real constructor:
VaR ocar = new car ();

Because the new operator is called inside the car () constructor, the second new operator (outside the constructor) is ignored ). Objects Created within the constructor are passed back to the variable VAR. This method has the same problems as the classic method in the internal management of object methods. It is strongly recommended that you do not use this method unless you have to (see Chapter 15th.
CONCLUSION: (which method is used)
Currently, the most widely used is the hybrid constructor/prototype method. In addition, the dynamic prototype method is also popular, which is functionally equivalent to the constructor/prototype method. Either of the two methods can be used. However, do not use the classic constructor or prototype alone, because this will introduce problems to the code.
// PS
// Static class (1: function)
VaR carcollection = new function (){
VaR _ carcollection = new array (); // global, private
This. Add = function (objcar ){
Alert ('add ');
}
This. Get = function (carid ){
Alert ('get ');
}
}

// Static class (2: JSON)

VaR car = {
Color: 'red ',
Doors: 4,
Showcolor: function () {alert (this. Color );}
}
Car. showcolor ();

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.