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 ());
}