Several ways to define JavaScript classes summarize _javascript techniques

Source: Internet
Author: User
Tags class definition mixed

We can think of classes, objects, encapsulation, inheritance, polymorphism, when we raise object-oriented objects. In "JavaScript Advanced Program Design" (People's Posts and telecommunications press, Cao Li, Zhang Xin translated. The English name is: Professional JavaScript for WEB developers is described in more detail in this book. Let's look at the various methods of defining classes in JavaScript.

1. Factory mode

JavaScript to create their own classes and objects, we should be mastered, we all know that the properties of the object in JavaScript can be dynamically defined after the object is created, such as the following code:

Copy Code code as follows:

<script type= "Text/javascript" >
Defined
var ocar = new Object ();
Ocar.color = "Red";
Ocar.doors = 4;
Ocar.showcolor = function () {
alert (This.color);
}
Call
Ocar.showcolor ();
</script>

It's easy to use Ocar objects, but we create multiple car instances. We can use a function to encapsulate the above code to implement:
Copy code code as follows:

<script type= "Text/javascript" >
Defined
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 properties for JavaScript objects are public. In this way we call the factory approach, and we create factories that can create and return specific types of objects.

This is a bit of an interesting thing to do, but the way we often use to create objects in object-oriented objects is:

Car car=new car ();

Using the New keyword is already popular, so we use the above method to define total feeling awkward, and to create new attributes and functions every time we call them, it is not practical. Down we look at the form definition class of the constructor.

2. Constructors

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

Copy Code code as follows:

<script type= "Text/javascript" >
Defined
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>

Looks like the effect is obvious, there is a difference. I feel a little bit interesting. Creating objects inside constructors using the This keyword, creating objects with the new operator feels very cordial. But there is also a problem: every time the new object will create all the attributes, including the creation of functions, that is, multiple objects are completely independent, we define classes to share methods and data, but CAR1 objects and Car2 objects are separate properties and functions, at least we should share the method. This is the advantage of the prototype approach.

3. Prototype mode

Using the prototype property of an object, you can see the prototype on which the new object is created. The method is as follows:

Copy Code code as follows:

<script type= "Text/javascript" >
Defined
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

You can simplify the definition of prototype in JSON mode:

Car.prototype =
{
Color: "Red",
Doors:4,
Drivers: ["Tom", "Jerry", ' Safdad '],
Showcolor:function () {
alert (This.color);
}
}
</script>


First, the constructor of this code, which does not have any code, then adds the property to define the properties of the car object through the object's prototype property. This is a good method, but the problem is that the car object is pointing to an array pointer, and two of the car's objects are pointing to the same array, with one object car1 changing the reference (array array) of the Property object, and the other object car2 at the same time, which is not allowed.

The problem also manifests that the prototype cannot take any initialization parameters, causing the constructor to not initialize properly. This needs to be solved in another way: the Hybrid constructor/prototype pattern.

4. Hybrid constructor/prototype pattern

Using constructors and prototypes together, it is convenient to define classes.

Copy Code code as follows:

<script type= "Text/javascript" >
Defined
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>


The method is to put the attribute in the internal definition, put the method outside using prototype to define. Solves the problem of the third method.

This method should actually be very friendly, but compared to Java syntax, there should be some disharmony, feel more messy, for C + +, we have less trouble feeling, but the development of C + + developers generally rarely involved in JavaScript, And for the developers of the Java EE, this approach is always somewhat awkward. The total feeling is not a friendly package, in fact, is only the visual packaging effect is not very good, to achieve visual packaging effect and can achieve the effect of this method can also be, personally think it is actually more troublesome. That's the dynamic prototyping method.

5. Dynamic Prototyping

For developers who are accustomed to using other languages, it feels less harmonious to use a mixed constructor/prototyping approach. After all, when defining classes, most object-oriented languages visually encapsulate properties and methods. Consider the following C # class:

Copy Code code as follows:

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 # Nicely packs all the properties and methods of the car class, so seeing this code knows what it's going to do, and it defines an object's information. Critics of the hybrid constructor/archetype approach argue that it is illogical to find a method in the constructor memory to find the attribute. As a result, they designed a dynamic prototyping approach to provide a more user-friendly coding style.

The basic idea of a dynamic prototyping method is the same as a mixed constructor/prototype approach, that is, to define the non function attribute within the constructor, and the function property to use the stereotype attribute definition. The only difference is where the object method is assigned. The following is a car class that is overridden with a dynamic prototyping method:

Copy Code code as follows:

<script type= "Text/javascript" >
Defined
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 does not change until you check that typeof car._initialized is equal to "undefined". This line of code is the most important part of the dynamic prototyping approach. If this value is undefined, the constructor will continue to define the object's methods in a prototype manner and then set car._initialized to True. If the value is defined (its value is true, the value of typeof is Boolean), the method is no longer created. In short, the method uses flags (_initialized) to determine whether any method has been given to the prototype. This method only creates and assigns values once, and this code looks more like a class definition in other languages to please traditional OOP developers.

6 Mixing Factory Way

This approach is usually a workaround when the previous method cannot be applied. It is designed to create a fake constructor and return only a new instance of another object. This code looks very similar to the factory function:

Copy Code code as follows:

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 approach, this method uses the new operator to make it look like a real constructor:
var ocar = new car ();

The second new operator (outside the constructor) is ignored because the new operator is called inside the car () constructor. Objects created inside the constructor are passed back to the variable var. This approach has the same problem with the classic approach to the internal management of object methods. It is highly recommended that you avoid using this method unless you have a last resort (see Chapter 15th).

Summary: (Which way to use)
The most widely used current is the hybrid constructor/prototyping approach. In addition, dynamic prototyping methods are also popular and functionally equivalent to the constructor/prototyping approach. Either of these two approaches can be used. However, do not use the classic constructor or prototyping alone, as this can introduce problems to your code.

Copy Code code as follows:

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.