JavaScript uses constructor and prototype to simulate functions of class C _ javascript skills

Source: Internet
Author: User
This article describes how JavaScript simulates the functions of class C # using constructor and prototype. For more information, see. The Code is as follows:


// Constructor
Function person (name, age ){
This. name = name;
This. age = age;
}
// Define the person prototype. attributes in the prototype can be referenced by custom objects.
Person. prototype = {
GetName: function (){
Return this. name;
},
GetAge: function (){
Return this. age;
}
}


The Code is as follows:


This requires the introduction of another concept-prototype. We can simply regard prototype as a template, and all newly created custom objects are prototype) A copy of (in fact, it is not a copy but a link, but this link is invisible, giving people the feeling that it is a copy ).
JavaScript simulates the class functions by using constructors and prototypes.
Window. onload = function (){
Person. prototype. sex = 'male ';
Var fmj = new person ('kkk ', 22 );
Alert ('first output: '+ fmj. sex );
Fmj. sex = 'confidential ';
Alert ('second output: '+ fmj. sex );
Delete fmj. sex;
Alert ('third output: '+ fmj. sex );
// Output the result on the debug console.
// Console. log (fmj. getAge ());
}

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.