Several ways to define Js class

Source: Internet
Author: User

Lifting object-oriented we can think of classes, objects, encapsulation, inheritance, polymorphism. In the JavaScript Advanced Program design (People's post and telecommunications press, Tianhua, Zhang Xin translation.) The English name is: Professional JavaScript for WEB developers) This book is described in more detail. Let's look at the various methods of defining classes in JavaScript.

1. Factory mode

JavaScript creates its own classes and objects that we should be able to master, and we all know that the properties of objects in JavaScript can be dynamically defined after object creation, such as the following code:

<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 the Ocar object, but we're creating multiple car instances. We can use a function to encapsulate the above code to implement: <script type= "Text/javascript";
   //Definition
    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 a factory that can create and return objects of a particular type.

This is a bit of a point, but in object-oriented we often use the method of creating objects:

Car car=new car ();

The use of the New keyword has been popular, so we use the above method to define the total feeling awkward, and every time we call to create new properties and functions, the function is not practical. Let's look at the formal definition class of the constructor.

2. constructor function

This approach looks a bit like a factory function. The specific performance is 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>

It seems that the effect is obvious, there is a difference. It feels a little bit interesting. Creating objects inside constructors uses the This keyword, and creating objects using the new operator feels very kind. But there's also a problem: Every new object creates all the properties, including the creation of the function, which means that multiple objects are completely independent, and we define the class to share the method and the data, but the Car1 object and the Car2 object are separate properties and functions, at least we should share the method. This is where the advantages of the prototype approach lie.

3. Prototype mode

The prototype property of an object can be used to see the prototype on which the new object is created. Here's how:

<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); Results: Tom,jerry,stephen
alert (car2.drivers); Results: 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 for this code, where there is no code, is then defined by adding properties to the object's prototype property to define the properties of the car object. This is a good approach, but the problem is that the object of car is pointing to an array pointer, and the two objects of car point to the same array of arrays, where one object car1 changing the reference (array) of the Property object, and the other object car2 also changes at the same time, which is not allowed.

At the same time, the problem also manifests that the prototype cannot take any initialization parameters, which causes the constructor to not initialize properly. This requires a different approach: the Hybrid constructor/prototype pattern.

4. Mixed constructor/prototype mode

In conjunction with constructors and prototypes, it is very convenient to define classes.

<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); Results: Tom,jerry,stephen
alert (car2.drivers); Results: Tom,jerry
Alert (car1 instanceof Car);

</script>

The method is to put the attributes in the internal definition, the method is placed outside the use of 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 are not so troublesome to feel, but the development of C + + developers generally rarely involved in JavaScript, For the developers of the Java EE, this approach is always somewhat awkward. The total feeling is not a friendly package, in fact, it is only the visual packaging effect is not very good, to achieve the visual packaging effect and can achieve the effect of this method can also, the individual think actually more troublesome. That's the dynamic prototyping method.

5. Dynamic Prototyping

For developers who are accustomed to using other languages, using mixed constructors/prototypes does not feel so harmonious. After all, when defining a class, most object-oriented languages visually encapsulate properties and methods. 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 # is good at packaging all the properties and methods of the car class, so seeing this code knows what it is going to do, and it defines the information for an object. Critics of mixed constructors/prototypes argue that the approach to finding a property in the constructor's memory is illogical in the way it is found outside. 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, where a non-function attribute is defined within a constructor, and a function attribute is defined using a prototype attribute. The only difference is where the object method is given. The following is the car class rewritten with the dynamic prototyping method:

<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 is not changed until the typeof car._initialized is checked to be 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 method of the object in a prototype manner, and then set the car._initialized to true. If the value is defined (its value is true, the value of typeof is Boolean), then the method is no longer created. In short, the method uses flags (_initialized) to determine whether any method has been assigned to the prototype. This method only creates and assigns a value once, and to delight the traditional OOP developer, this code looks more like a class definition in other languages.

6 Hybrid Plant Approach

This approach is usually a workaround when the previous method cannot be applied. Its purpose is to create a false constructor that returns only a new instance 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 approach, this approach 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 of the constructor) is ignored. Objects created inside the constructor are passed back to the variable var. This approach has the same problem as the classic approach in the internal management of object methods. It is strongly recommended that you avoid using this method unless you have to do so (see Chapter 15th).
Summary: (which method to use)
The most widely used is the hybrid constructor/prototype approach. In addition, the dynamic prototyping approach is also popular, functionally equivalent to the constructor/prototype approach. Either of these two approaches can be used. Do not use classic constructors or prototypes alone, however, because it introduces problems to your 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 ();

Several ways to define Js class

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.