国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JS中prototype關鍵字的功能介紹及使用示例

2019-11-20 22:30:14
字體:
來源:轉載
供稿:網友
prototype 關鍵字可以為 JS原有對象 或者 自己創建的類 中添加方法或者屬性。
也可以實現繼承。
例子:
復制代碼 代碼如下:

<!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>JS中 prototype 關鍵字的使用</title>
</head>
<script>
<!-- demo1 JS中原有對象中 添加方法 -->
Number.prototype.add = function (num){
return this+num;
}
function but1_click(){
alert((3).add(8));
}
<!-- demo2 JS中新建對象中, 添加屬性 ,方法 -->
function Car(cColor,cWeight){
this.cColor = cColor;
this.cWeight = cWeight;
}
Car.prototype.drivers = new Array('zhangsan','lisi');
Car.prototype.work = function (cLong){
alert("我跑了"+cLong+"公里");
}
function but2_click(){
var c = new Car("red","5");
c.drivers.push('zhaoliu');
alert(c.drivers);
c.work(1);
}
<!-- demo3 JS中新建對象中, 添加屬性 ,方法 緊湊的寫法 -->
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 繼承 -->
function objectA(){
this.methodA = function (){
alert("我是A方法");
}
}
function objectB(){
this.methodB = function (){
alert("我是B方法");
}
}
objectB.prototype = new objectA();
function but4_click(){
var t = new objectB();
t.methodB();
t.methodA();
}
</script>
<body>
<h2> prototype 關鍵字的使用 </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>
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新化县| 枣庄市| 河曲县| 郧西县| 和静县| 汉沽区| 弥勒县| 武义县| 林芝县| 通州区| 射阳县| 犍为县| 屏东县| 大埔区| 五峰| 涿州市| 二连浩特市| 衡阳市| 山阳县| 延吉市| 阳信县| 日土县| 张家川| 岚皋县| 缙云县| 临城县| 台北县| 察哈| 贵州省| 巴彦县| 长沙县| 吉木萨尔县| 承德县| 大英县| 双江| 荔波县| 遵义县| 新密市| 沁阳市| 延寿县| 太康县|