The prototype keyword can add a method or property to a JS original object or to a class that you create.
You can also implement inheritance.
Example:
Copy Code code 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 "/>
Use of prototype keywords in
<title>js </title>
</head>
<script>
<!--Demo1 JS Central has an object to add methods-->
Number.prototype.add = function (num) {
return this+num;
}
function But1_click () {
Alert ((3). Add (8));
}
<!--Demo2 js new object, add properties, method-->
function Car (ccolor,cweight) {
this.ccolor = Ccolor;
This.cweight = Cweight;
}
Car.prototype.drivers = new Array (' Zhangsan ', ' 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);
}
<!--Demo3 js new object, add attributes, method compact-->
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>
Use of
<h2> prototype keywords </h2>
<hr/>
<input id= "but1" type= "button" value= "Demo1" onclick= "But1_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>