JavaScript Common object class creation code and pros and Cons analysis _js object-oriented

Source: Internet
Author: User
There are several ways to build a class in javascript:
1.Factory Mode
Copy Code code as follows:

function Createcar () {
var car = new Object ();
Car.color= "B";
car.length=1;
Car.run=function () {alert ("Run");}
return car;
}

Once you have defined such a function, you can use:
var car1 = Createcar ();
var car2 = Createcar ();
To create a new object, the problem is that every time you create a car object, the run function must be re-created once. Wasting memory

2.Constructor Mode
Copy Code code as follows:

function car () {
This.color= "B";
this.length=1;
This.run=function () {alert ("Run");}
}
var car1=new car ();
var car2=new car ();

This is the most basic way, but it has the same problems as the factory way.

3.prototype Mode
Copy Code code as follows:

function car () {
}
Car.prototype.color= "B";
car.prototype.length=1;
Car.prototype.run=function () {alert ("Run");
}

The disadvantage of this approach is that when this class has a reference property, changing the property of an object also changes the properties of the other object.
Like what:
Copy Code code as follows:

Car.prototype.data1=new Array ();
var car1=new car ();
var car2=new car ();
Car1.data1.push ("a");

At this point, Car2.data also contains the "a" element

4.prototype/constructor Hybrid MethodCommon
Copy Code code as follows:

function car () {
This.color= "B";
this.length=1;
This.data1=new Array ();
}
Car.prototype.run=function () {
Alert ("dddd");
}


This way to go beyond those shortcomings. is currently a wide range of ways to use

5. Dynamic prototype method [commonly used]
Copy Code code as follows:

function car () {
This.color= "B";
this.length=1;
This.data1=new Array ();

if (typeof car.initilize== "undefined") {
Car.prototype.run=function () {alert ("a");}
}

Car.initilize=true;
}

In these ways, the most commonly used is the hybrid Prototype/constructor and dynamic prototype mode.
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.