zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JS中prototype关键字的功能介绍及使用示例

JS 使用 功能 介绍 示例 关键字 prototype
2023-06-13 09:15:03 时间
prototype关键字可以为JS原有对象或者自己创建的类中添加方法或者属性。
也可以实现继承。
例子:
复制代码代码如下:

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>JS中prototype关键字的使用</title>
</head>
<script>
<!--demo1JS中原有对象中添加方法-->
Number.prototype.add=function(num){
returnthis+num;
}
functionbut1_click(){
alert((3).add(8));
}
<!--demo2JS中新建对象中,添加属性,方法-->
functionCar(cColor,cWeight){
this.cColor=cColor;
this.cWeight=cWeight;
}
Car.prototype.drivers=newArray("zhangsan","lisi");
Car.prototype.work=function(cLong){
alert("我跑了"+cLong+"公里");
}
functionbut2_click(){
varc=newCar("red","5");
c.drivers.push("zhaoliu");
alert(c.drivers);
c.work(1);
}
<!--demo3JS中新建对象中,添加属性,方法紧凑的写法-->
functionRectangle(rWeight,rHeight){
this.rWeight=rWeight;
this.rHeight=rHeight;
if(typeofthis._init=="undefined"){
Rectangle.prototype.test=function(){
alert("test");
}
}
this._init=true;
}
functionbut3_click(){
vart=newRectangle(6,8);
t.test();
}
<!--demo4prototype继承-->
functionobjectA(){
this.methodA=function(){
alert("我是A方法");
}
}
functionobjectB(){
this.methodB=function(){
alert("我是B方法");
}
}
objectB.prototype=newobjectA();
functionbut4_click(){
vart=newobjectB();
t.methodB();
t.methodA();
}
</script>
<body>
<h2>prototype关键字的使用</h2>
<hr/>
<inputid="but1"type="button"value="demo1"onclick="but1_click()"/>
<inputid="but2"type="button"value="demo2"onclick="but2_click()"/>
<inputid="but3"type="button"value="demo3"onclick="but3_click()"/>
<inputid="but4"type="button"value="demo4"onclick="but4_click()"/>
</body>
</html>