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>
相关文章
- Tone.js基础使用
- arraylist遍历 并删除_js遍历list对象
- 浅谈与使用js中的原型
- 使用git webhook自动部署代码(PHP,HTML/JS)
- JS的异步编程过程中的问题集锦、echarts使用记录。
- node.js报错:Cannot find module ‘ejs’的解决办法详解编程语言
- JS 计算问题详解编程语言
- JS navigator对象详解
- JS使用函数封装图片切换功能
- 使用Node.js连接MongoDB数据库的方法及实践(连接mongodb)
- 使用 JS 操作 Redis:实现强大数据存储.(js调用redis)
- 使用JS技术实现Oracle数据库链接(js 链接 oracle)
- 使用JS控制Oracle数据库的更新(js控制oracle更新)
- JS将文件传输至MySQL数据库(.js传文件至mysql)
- Oracle中使用JS变量管理数据(oracle使用js变量)
- js页面左右两侧居中广告代码
- js调用webservice中的方法实现思路及代码
- 用js实现控件的隐藏及style.visibility的使用
- JS截取字符串常用方法整理及使用示例
- JS中表单的使用小结
- node.js使用npm安装插件时提示installError:ENOENT报错的解决方法
- yepnope.js使用详解及示例分享
- node.js中的console.timeEnd方法使用说明
- node.js中的http.get方法使用说明
- node.js中的fs.stat方法使用说明