Four Methods for defining javascript classes

Source: Internet
Author: User
Tags define function

Copy codeThe Code is as follows:
/*
Factory method --- create and return the factory function of a specific type of object)
*/
Function createCar (color, doors, mpg ){
Var tempCar = new Object;
TempCar. color = color;
TempCar. doors = doors;
TempCar. mpg = mpg;
TempCar. showCar = function (){
Alert (this. color + "" + this. doors );
}
Return tempCar;
}

/*
Constructor method --- constructor looks like a factory function
*/
Function Car (color, doors, mpg ){
This. color = color;
This. doors = doors;
This. mpg = mpg;
This. showCar = function (){
Alert (this. color );
};
}
/*
Prototype Method-the prototype attribute of an object can be used to create a prototype on which the object depends.
*/
Function Car (color, doors, mpg ){
This. color = color;
This. doors = doors;
This. mpg = mpg;
This. drivers = new Array ("nomad", "angel ");
}

Car. prototype. showCar3 = function (){
Alert (this. color );
};

/*
Hybrid constructor/prototype-use constructor to define all non-function attributes of an object, and use prototype to define function attributes (methods) of an object)
*/
Function Car (sColor, iDoors, iMpg ){
This. color = sColor;
This. doors = iDoors;
This. mpg = iMpg;
This. drivers = new Array ("Mike", "Sue ");
}

Car. prototype. showColor = function (){
Alert (this. color );
};
/*
Dynamic Prototype Method-non-function attributes are defined in the constructor, while function attributes are defined using the prototype attributes. The only difference is that the location of the object method is assigned.
*/
Function Car (sColor, iDoors, iMpg ){
This. color = sColor;
This. doors = iDoors;
This. mpg = iMpg;
This. drivers = new Array ("Mike", "Sue ");

If (typeof Car. _ initialized = "undefined "){

Car. prototype. showColor = function (){
Alert (this. color );
};

Car. _ initialized = true;
}
} // This method uses the sign (_ initialized) to determine whether any method has been granted to the prototype.

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.