Javascript-based constructor/prototype

Source: Internet
Author: User

Using constructor and prototype together, you can create objects just like using other programming languages. This concept is very simple, that is, using constructors to define all non-function attributes of an object and using prototype to define the function attributes (methods) of an object ). Result All functions are created only once, and each object has its own object attribute instance.

 

Code
// Mixed constructor/prototype
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 );
}

VaR ocar1 = new car ("red", 4,23 );
VaR ocar2 = new car ("blue", 3,33 );
Ocar1.drivers. Push ("Matt ");
Ocar1.drivers (); // output Mike, Sue, Matt
Ocar2.drivers (); // output Mike, Sue

Now it is more like creating a common object. All non-function attributes are created in the constructor, which means that the default values of the attributes can be assigned to the constructor parameters. Because only one instance of the showcolor () function is created, there is no memory waste. In addition, adding the "Matt" value to the drivers array of ocar1 does not affect the ocar2 array. Therefore, when outputting the values of these arrays, ocar1.drivers displays "Mike, Sue, Matt ", ocar2.drivers displays "Mike, Sue ".

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.