The prototype keyword can be used to add methods or attributes to the original JS object or a self-created class.
You can also implement inheritance.
Example:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> Use of prototype keywords in JS </title>
</Head>
<Script>
<! -- Demo1 JS original object addition method -->
Number. prototype. add = function (num ){
Return this + num;
}
Function butaskclick (){
Alert (3). add (8 ));
}
<! -- In demo2 JS, create an object and add attributes. Method -->
Function Car (cColor, cWeight ){
This. cColor = cColor;
This. cWeight = cWeight;
}
Car. prototype. drivers = new Array ('hangsan', 'lisi ');
Car. prototype. work = function (cLong ){
Alert ("I ran" + cLong + "km ");
}
Function but2_click (){
Var c = new Car ("red", "5 ");
C. drivers. push ('zhaoliu ');
Alert (c. drivers );
C. work (1 );
}
<! -- Add attributes to new objects in demo3 JS and compact the method -->
Function Rectangle (rWeight, rHeight ){
This. rWeight = rWeight;
This. rHeight = rHeight;
If (typeof this. _ init = 'undefined '){
Rectangle. prototype. test = function (){
Alert ("test ");
}
}
This. _ init = true;
}
Function but3_click (){
Var t = new Rectangle (6, 8 );
T. test ();
}
<! -- Demo4 prototype inheritance -->
Function objectA (){
This. methodA = function (){
Alert ("I Am A method ");
}
}
Function objectB (){
This. methodB = function (){
Alert ("I Am a B method ");
}
}
ObjectB. prototype = new objectA ();
Function but4_click (){
Var t = new objectB ();
T. methodB ();
T. methodA ();
}
</Script>
<Body>
<H2> Use of prototype keywords <Hr/>
<Input id = "but1" type = "button" value = "demo1" onclick = "butw.click ()"/>
<Input id = "but2" type = "button" value = "demo2" onclick = "but2_click ()"/>
<Input id = "but3" type = "button" value = "demo3" onclick = "but3_click ()"/>
<Input id = "but4" type = "button" value = "demo4" onclick = "but4_click ()"/>
</Body>
</Html>