Object-oriented javascript Learning

Source: Internet
Author: User

1. Factory Model
Function showColor (){
Alert (this. color );
} // Ensure that this function has only one backup

Function createCar (){
Var tmpCar = new Object;
TmpCar. color = "red ";
TmpCar. name = "fff ";
TmpCar. showColor = showColor;
Return tmpCar;
}

Var car1 = createCar ();
Var car2 = createCar ();
2. constructor Method
Function Car (){
This. color = 1;
This. name = "f ";
}
Var car = new Car ();
3. Prototype
Function Car (){
}
Car. prototype. color = 12;
Car. prototype. drivers = new Array (1, 2 );

Var car1 = new Car ();.
Var car2 = new Car ();
Car1.drivers. push (3 );
Then, the drivers of two cars will change to 1, 2, and 3 because the two share an array address. The constructor cannot be passed in.

4. Mixed constructor and prototype
Use constructor to construct properties use prototype to construct shared Functions
Function Car (parameter ){
This. color = xxx;
This. name = xxx;
}
Car. prototype. show = function (){
Xxxx
}

5. Traditional programmers of oop have a dynamic prototype method.
Function Car (){
This. color = xxx;
This. name = xxx;
This. drivers = new Array (aa, bb );
If (typeof Car. _ initialized = "undefined "){
Car. prototype. show = function (){
Xxxxxs
}
}
Author: carmazhao

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.